obj.x, end to endThe most frequent line in the language and one of the deepest gaps in understanding. A single four-step procedure explains descriptors, property, explicit self, __slots__, metaclasses, and why mypy cannot be sound even in principle.
Four snippets. Commit to an output and a reason before you open the answer.
class A:
x = 1
a = A()
print(a.x)
a.x = 2
print(a.x, A.x)
del a.x
print(a.x)
1
2 1
1The instance attribute appeared, shadowed the class one, disappeared — and the class one came back.class B:
@property
def v(self): return 1
b = B()
b.__dict__['v'] = 99
print(b.v)
1The value was put straight into the instance dictionary — and ignored.class C:
__slots__ = ('x',)
c = C()
c.y = 1
AttributeError: 'C' object has no attribute 'y'And yet c.x = 1 works just fine.class D:
def __getattr__(self, name):
return f"no such thing: {name}"
d = D()
print(d.foo)
d.foo = 1
print(d.foo)
no such thing: foo
1The same d.foo, two different sources of the answer.The first thing to accept: obj.x is not a field read. It is a call. The compiler turns the dot into a request to the object's type, and from there a procedure runs that has exactly four steps in a strict order. The whole lesson is about that order.
Before writing it out, one concept is needed. A descriptor is an object that defines __get__. If it also has __set__ or __delete__, it is called a data descriptor. If it has only __get__, it is a non-data descriptor. The difference between these two kinds is the whole plot.
obj.xStep 1. Look for x in the object's type and every class in its MRO. If it is found and it is a data descriptor, call its __get__. Done.
Step 2. Otherwise look in the instance's own data. Found — return it. Done.
Step 3. Otherwise go back to what was found on the class in step 1. A non-data descriptor — call __get__; a plain value — return it as is. Done.
Step 4. Found nowhere — call __getattr__ if it is defined. Otherwise AttributeError.
Four steps. Now all four snippets fall out by direct application.
At first x exists only on the class and is not a descriptor — step 3 fires and we see 1. The assignment a.x = 2 puts the value into the instance's data, and now step 2 fires before step 3: the instance sees 2, the class still has 1. del a.x removes the instance entry, step 2 finds nothing again, and step 3 returns the class value. Nothing was “overwritten” — what changed is which step gets there first.
property cannot be shadowedproperty is neither syntax nor magic. It is an ordinary object with __get__, __set__ and __delete__ — that is, a data descriptor sitting on the class. So step 1 fires and the instance dictionary is never even consulted. The value 99 sits in b.__dict__ and is unreachable.
The same reasoning yields something usually memorized separately: assigning to a property without a setter fails not because “a property is read-only”, but because its __set__ is always defined and simply raises AttributeError.
__slots__ is__slots__ does two things. It removes __dict__ from the instance — that is, it switches step 2 off entirely. And it creates one data descriptor on the class per declared name, each of which reads and writes at a fixed offset inside the object.
Everything else follows. c.x works because step 1 finds the slot descriptor. c.y = 1 fails because there is no descriptor y on the class and nowhere else to put the value — step 2 does not exist. And it becomes clear why __slots__ saves memory: a whole dictionary per object disappears.
__getattr__ is step 4, not step 0The first access to d.foo goes through all three steps for nothing and lands on the fourth. After d.foo = 1 the value is in the instance's data and step 2 answers first — __getattr__ is never called again. That is the only reason the output differs: the “interceptor” did not switch off, the lookup simply started succeeding earlier.
This is also where the most commonly confused distinction lives. __getattribute__ is the entire procedure; it is called on every access. __getattr__ is only the fallback exit at step 4. Overriding the former is dangerous precisely because any attribute access inside it calls it again.
Why self is explicit. A function written in a class body is a non-data descriptor: it has __get__ and no __set__. So q.m goes through step 3, calls __get__, and what comes back is not the function but a bound method — an object that remembers the instance and will pass it as the first argument.
print((type(Q.m), type(q.m)))
# → (<class 'function'>, <class 'method'>)
print(q.m.__self__ is q)
# → True
print(Q.__dict__['m'].__get__(q, Q))
# → <bound method Q.m of <__main__.Q object>>
Explicit self is not a stylistic choice and not a “tribute to explicitness”. It is the only way to write the signature of a function that will become a bound method through a descriptor. And the same line explains why Q.m(q) works: taken from the class, the function is fetched directly, without step 3, and the first argument has to be passed by hand.
What classmethod and staticmethod are. The same non-data descriptors, only with a different __get__: the first passes the class instead of the instance, the second passes nothing. Three decorators — one mechanism and three variants of one method.
Why mypy cannot be sound even in principle. The whole procedure runs at execution time and depends on what is in the class and the instance right now. A class can be changed after creation, a descriptor swapped in at runtime, and __getattr__ can synthesize any name. A static analyzer has to assume none of that happened. It is useful, but its conclusions are not proofs.
Dunders are looked up outside this procedure. When the interpreter itself calls a special method — len(obj), obj + x, with obj — it goes straight to the type, bypassing both the instance and __getattr__. That is why a proxy object that synthesizes any name through __getattr__ still will not become iterable: __iter__ cannot be supplied that way 🔒. The procedure above describes the explicit access obj.x, not implicit calls.
For a class the procedure is different. A.x is an attribute access on the class object, and it works through the class's type, that is, through the metaclass. Hence a property on a metaclass is visible on the class but not on its instances.
“The instance's data” is not necessarily __dict__. Since 3.11 the attribute values of an ordinary object physically live not in a separate dictionary but in an area next to the object, and the dictionary is materialized on demand 🔧. Behaviour is unaffected — memory and speed are affected a lot. Details in L2.
The decision everything grew from: an attribute is not resolved ahead of time — it is looked up at the moment of access, and an object's namespace is mutable while the program runs.
Early Python had this property almost by accident, as a consequence of a simple implementation. It became a deliberate decision in 2001, when Guido was unifying types and classes: descriptors, the MRO and property appeared then — and all of it was built on top of dynamic lookup, not in place of it. At that point the language could have fixed object layouts and become faster. Instead it got a single mechanism through which property, methods, slots, ORMs and validators are all expressed — at the price that every attribute access costs work.
That price went unpaid for twenty years and was one of the main reasons for the “Python is slow” reputation. It was paid in 3.11: the interpreter learned to remember the result of a lookup right in the bytecode stream. The mechanism did not change — what changed is that from the second time on it no longer runs in full.
The MRO is a linear extension of a partial order. Inheritance defines a relation on classes, the diamond makes it genuinely partial, and C3 builds a linearization in which every class appears once, a descendant always comes before its ancestor, and the order of base classes from the declaration is preserved. If no compatible linear order exists, the class will not be created — and that is an error at declaration time, not at call time.
class X: pass
class Y(X): pass
class Z(X): pass
class W(Y, Z): pass
print([c.__name__ for c in W.__mro__])
# → ['W', 'Y', 'Z', 'X', 'object']
This makes it immediately clear what super() is not. It does not “call the parent”: it hands control to the next class in this linearization — and next after Y here is Z, which is not a parent of Y at all. That is exactly why cooperative multiple inheritance works, and exactly why it breaks if even one class in the chain fails to call super().
Questions that come up on their own if you read closely. The answer is under the question.
self explicit — couldn't it have been passed automatically?Because that would require a special kind of function, and a method is an ordinary function.
The mechanics are in this lesson: a function is a non-data descriptor, and when accessed through an instance its __get__ returns a bound method with the first argument already filled in. The language has no “method declaration” — there is a function in a class body.
class C:
def m(self): return self
c = C()
print(C.m) # → a plain function
print(c.m) # → bound method
print(c.m.__self__ is c) # → True
print(C.m(c) is c.m()) # → True one and the same
Everything else follows from this: a function can be attached to a class after it is created, a method can be passed around as an ordinary callable, and you can call C.m(instance) directly — which is what super() does inside.
The second argument is readability. In C++ and Java a field accessed without this is visually indistinguishable from a local variable, and that is a source of bugs. In Python self.x and x are different things and look different. Guido considered that reason enough on its own.
The price is a few extra characters in every signature and the classic “forgot self” error. The trade is deliberate and recorded in PEP 20: explicit is better than implicit.
__slots__ gives both memory and speed, why is it not the default?Because it forbids what half the ecosystem stands on: adding attributes after creation.
class S:
__slots__ = ("x",)
s = S()
s.y = 1
# → AttributeError: 'S' object has no attribute 'y'
This breaks: monkey-patching in tests, caching a computed value on the instance, mixins that add fields, ORMs and serializers that hang service attributes on objects, functools.cached_property, weak references (unless __weakref__ is added explicitly). On top of that, multiple inheritance from two classes with non-empty __slots__ simply does not work.
The gain is real, but more modest than the advice suggests. Measured in this lesson: 56 bytes per instance versus 96 for an ordinary class — and versus 160 if some code has touched obj.__dict__. In attribute read speed there is almost no difference:
plain 0.077 s per 2M reads
__slots__ 0.081 s
property 0.185 s
The rule: __slots__ is justified where there are hundreds of thousands of objects and they are all alike — points, records, graph nodes. For twenty service objects it is pure harm. And first check whether dataclass(slots=True), or simply an array instead of objects, would do.
Because almost no search takes place: the inline cache remembers the result right in the instruction.
A measurement from lesson 23: 6 ns per bytecode instruction, and the difference between reading a local and reading an attribute is lost in the noise of the loop. That does not mean the four-step procedure is not executed — it means that in the typical case it is executed once, and after that a single equality check on the type version is performed.
import dis
class P:
def __init__(self): self.x = 1
p = P()
def get(o): return o.x
for _ in range(200): get(p)
dis.dis(get, adaptive=True)
# → LOAD_ATTR_INSTANCE_VALUE instead of the generic LOAD_ATTR
But the bet is checked, and it can be lost. If objects of different types arrive at the same access site, the cache misses and the instruction is deoptimized. A measurement from lesson 21: iterating a homogeneous collection is 1.4 times faster than a mix of three classes with completely identical code.
property, however, gets no help from the cache: there a function really is called on every read, and that is 2.4 times on top of a plain attribute. The practical upshot: a property for a computed value is fine; a property wrapper around a simple field “for the future” is a cost with no gain.
__getattr__ needed at all, if there is __getattribute__?Because one of them is safe and the other is a loaded gun.
__getattribute__ is called on every attribute access and replaces the whole procedure. Writing it correctly is next to impossible: any access to self.anything inside it recurses, and forgetting to call object.__getattribute__ for the ordinary case means breaking the object entirely.
__getattr__ is called only when the standard procedure has not found the attribute. So ordinary fields work as usual and at the usual price, and the interception fires only on a miss.
class Lazy:
def __getattr__(self, name): # only on a miss
print("miss:", name)
return 42
o = Lazy()
o.x = 1
print(o.x) # → 1 __getattr__ was not called
print(o.whatever) # → miss: whatever / 42
The practical consequence: proxies, lazy wrappers and API clients with dynamic methods are written with __getattr__. __getattribute__ is justified roughly never in application code — and if it has turned up in someone else's library, it is the first place to look when behaviour is baffling or performance sags.
And separately: neither of them intercepts dunders on an implicit call — len(x) goes to the type slot, past the whole procedure. Lesson 11 covers this.
obj.x is a call to a four-step procedure: a data descriptor on the class, then the instance's data, then everything else from the class, then __getattr__. property beats the instance dictionary because it sits on the first step; cached_property loses to it from the second access on because it sits on the third and writes into the second; __slots__ removes the second step altogether; self is explicit because a function is a non-data descriptor and __get__ returns a bound method. All of it runs at runtime and depends on the current state of the class — hence both the impossibility of sound static inference and twenty years of slow attribute access, paid off by inline caches in 3.11.
JavaScript made exactly the same decision — dynamic lookup along the prototype chain — and ran into the same price ten years earlier. V8's answer in 2008: hidden classes plus inline caches. Python reached the same conclusion in 2022. Same problem, same solution, a gap of a decade and a half — a good illustration that this is a property of the model, not of anyone's implementation.
C++ is the most precise point of comparison. A virtual call there is indirect too: the object carries a pointer to a vtable, and the call goes through a fixed offset in it. But that offset is computed by the compiler and never changes, and non-virtual fields are read at a constant displacement from the start of the object. Python does exactly the same thing — looks up by name and reads at an offset — only it computes that offset at runtime and re-caches it after every change to the class. The inline cache from the L2 section is precisely an attempt to get close to a vtable without giving up the ability to rewrite a class on the fly.
Java resolves a field statically at compile time. An access costs one instruction, and that is fast. But you can no longer slip a property in there — you need a getter written in advance; a field cannot be swapped at runtime; an ORM has to generate bytecode. The speed is bought by giving up flexibility, not obtained for free.
A cache for a computed value. It works, it is covered by tests, and in production it serves stale numbers.
class Cart:
def __init__(self, items):
self.items = items
@cached_property
def total(self):
return sum(i.price for i in self.items)
Later in the code the cart is topped up — and the total does not change:
cart = Cart([Item(10), Item(20)])
print(cart.total)
# → 30
cart.items.append(Item(70))
print(cart.total)
# → 30
print(cart.__dict__)
# → {'items': [...], 'total': 30}
After section 6 this is no longer a surprise but a direct consequence: the first access went through step 3, the descriptor computed 30 and put the result into the instance dictionary. From the second time on, step 2 finds it first and the method is never called again. There is no invalidation — there is nowhere to put it, because the descriptor no longer takes part in this scenario.
Why review lets it through: @cached_property reads as “cheaper to compute once” and looks like a harmless optimization. Tests usually create an object, read total and check the number — the “changed it and read again” scenario is not in them. And in production the cart lives between requests.
From here there is a fork, and it is a substantive one. If the object is immutable, cached_property is ideal. If it is mutable, you need either a plain property (compute every time), or an explicit reset self.__dict__.pop("total", None) on mutation, or a frozen object and re-creation. The right choice depends on which costs more — recomputation or the risk of staleness — and now that choice is made deliberately, not out of habit.
Two things that together give a multiple-fold effect on hot code, and both follow from the lookup procedure.
First — remove the dictionary from mass-produced objects. Two hundred thousand instances of a class with two fields:
| class | per object | 200,000 objects |
|---|---|---|
| plain | 128 B | 25.6 MB |
with __slots__ | 88 B | 17.6 MB |
A third of the memory for one line of declaration. The saving comes from step 2 being gone: instead of per-object storage there are descriptors with fixed offsets on the class.
Second — keep the hot loop homogeneous. One and the same function summing o.v over thirty thousand objects; in the first case all objects are of one class, in the second three classes are mixed:
| loop | 200 passes |
|---|---|
| objects of one class | 0.063 s |
| three classes mixed | 0.088 s |
A factor of 1.4 with completely identical code. The reason is in the L2 section: the inline cache stores one type version, so on a homogeneous collection the version check always passes, while on a heterogeneous one it misses on every third element and falls back to the generic lookup path.
The practical conclusion, which otherwise looks like superstition: sorting a heterogeneous collection into homogeneous lists and processing them one after another can be cheaper than a single pass over the mix. And a profiler will not tell you this — it will show that the time goes into the loop, but why it goes there is visible only from the mechanism.
Measured on CPython 3.11, linux x86-64. On another version the numbers will differ; the ratio will not.
Run the four snippets and check them against your prediction. Then four questions whose answers follow from the procedure but are not given in the text:
# 1. What will this print, and why?
class F:
def __getattr__(self, n): return "fallback"
@property
def p(self): raise AttributeError("oops")
print(F().p)
# 2. Why will this NOT call __getattr__?
class G:
def __getattr__(self, n): return lambda: 0
len(G())
# 3. Make an attribute that is readable on the class but not on an instance.
# 4. Why does cached_property not work with __slots__,
# while a plain property does?
The first question is the most useful one: it shows that the steps of the procedure are not isolated, and an AttributeError from inside a property is indistinguishable from “attribute not found”.
functools.cached_property is thirty lines in which the procedure from section 2 is used as a technique. It is a non-data descriptor: it has __get__ and deliberately no __set__.
class E:
@cached_property
def z(self):
print("computing")
return 42
e = E()
print(e.z)
# → computing
# → 42
print(e.z)
# → 42
print(e.__dict__)
# → {'z': 42}
Notice why nothing is printed the second time. On the first access step 2 has nothing to find — the instance is empty — so step 3 fires, the descriptor computes the value and puts it into the instance dictionary under the same name. From the second time on, step 2 finds it first and the descriptor is never called again. The cache works not because something is remembered inside, but because step 2 comes before step 3.
And right away a consequence that otherwise looks arbitrary: cached_property does not work on classes with __slots__. There is nowhere to put the value — step 2 does not exist.
Compare with property in the same Lib/functools.py and in Objects/descrobject.c: that one is a data descriptor, so it is always called. One protocol, two kinds, opposite behaviour — and the whole difference is the presence of __set__.
From L1 you know the order of the four steps. Here: where “the instance's data” actually lives, and why a repeated access is cheaper than the first.
A dictionary per object is expensive. A naive implementation would give every object a full dictionary:
class P: pass
p = P(); p.x = 1
print((sys.getsizeof(p), sys.getsizeof(p.__dict__)))
# → (56, 296)
class S: __slots__ = ('x',)
print(sys.getsizeof(S()))
# → 40
Three hundred bytes for an object with one attribute is unacceptable if there are a million objects. So CPython has two levels of optimization.
Shared keys. All instances of one class almost always have the same set of attribute names. So the names can be stored once per class, and the object holds only an array of values. That is what is done: the instance dictionary is split into a shared key table and a private array of values. Since 3.11 this array sits in memory right before the object, and a real __dict__ is assembled only if someone asks for it 🔧 — hence the advice not to touch __dict__ without need: accessing it materializes the dictionary and undoes the optimization.
The inline cache. Even with fast storage, every obj.x is a lookup. Starting with 3.11 the LOAD_ATTR instruction carries service cells next to it and after a few executions replaces itself with a specialized variant: remember the type version and the offset, then check the version and read at the offset. You can watch it straight from Python:
import dis
def f(o): return o.x
print(dis.dis(f, adaptive=True))
# → LOAD_FAST 0 (o)
# → LOAD_ATTR 0 (x)
for _ in range(100): f(p)
print(dis.dis(f, adaptive=True)) # after warm-up
# → LOAD_ATTR_INSTANCE_VALUE 0 (x)
The instruction changed itself. Any change to the class bumps its version and invalidates the cache — flexibility is still paid for, only now just by those who use it.
Hence a practical conclusion that sounds like knowledge of internals in an interview but is in fact derived: a hot loop in which the object's class is different every time loses specialization, and obj.x there costs noticeably more than in a loop over a homogeneous collection.
Tag v3.11.15. Read in this order.
Objects/object.c, function _PyObject_GenericGetAttrWithDict — the procedure from section 2, literally. Find the check f != NULL && PyDescr_IsData(descr) in it: that is step 1.Objects/typeobject.c, mro_implementation — the C3 linearization. The merge procedure itself takes a page.Objects/funcobject.c, func_descr_get — the three lines that make self explicit.Python/specialize.c, _Py_Specialize_LoadAttr — how the decision to specialize an instruction is made, and the reasons specialization fails. The list of failure reasons is instructive in itself.__slots__ versus shared keys: two ways not to pay for a dictionary per object, with different trade-offs__set__, and the behaviour is opposite@property and @classmethod as special cases of one mechanismproperty, classmethod and functions. Read it in full.