Attribute Access: The `__dict__` Lookup Tax & MRO Cost

Python objects typically store attributes in a dynamic dictionary (`__dict__`), making attribute access a hash table lookup, which is inherently slower than direct memory access in compiled languages. For inherited attributes, Python must also traverse the Method Resolution Order (MRO) of classes, further increasing lookup overhead.

The top 3

  1. __slots__: The Top Method to Skip `__dict__` Tax: Using `__slots__` in Python classes significantly speeds up attribute access by storing attributes directly in the object's memory layout, bypassing the slower `__dict__` lookup and reducing memory footprint.
  2. MRO's C3 Algorithm: The Standard for Class Resolution: Python's Method Resolution Order (MRO) for attribute and method lookup in inheritance is determined by the C3 linearization algorithm, ensuring a consistent, deterministic order across complex class hierarchies.
  3. Hidden Boost: Python's Attribute Lookup Caches: Python internally optimizes repeated attribute access through various caching mechanisms, particularly on type objects, to avoid re-computing the full lookup path for frequently accessed attributes.

Sources

Open the full topic