Sub topic 6
The complete lookup order
This chapter assumes you have read the earlier chapters on instance and class __dict__, the method resolution order (MRO), and the descriptor protocol with data and non-data descriptors. Here we combine those pieces into one ordered procedure and test it against edge cases.
The five steps
When you write obj.name, Python calls type(obj).__getattribute__(obj, "name"). For ordinary classes that is object.__getattribute__, which follows this order:
- Search
type(obj).__mro__forname. Call the first matchattr. Only the class hierarchy is searched here, never the instance. - If
attris a data descriptor (its type defines__get__plus__set__or__delete__), returntype(attr).__get__(attr, obj, type(obj)). - Otherwise, if
nameis a key inobj.__dict__, return that value. - Otherwise, if
attrexists, return it. If its type defines__get__(a non-data descriptor), return the result of calling__get__. If not, returnattrunchanged. - Otherwise raise
AttributeError. If the class defines__getattr__, Python then callstype(obj).__getattr__(obj, "name")and returns its result.
The MRO search happens first even though the instance wins in step 3. Python must know whether the class attribute is a data descriptor before it can decide whether the instance __dict__ is allowed to answer.
Outcomes at a glance
| Class attribute | Instance `__dict__` entry | `obj.name` returns |
|---|---|---|
| Data descriptor | present or absent | Result of the descriptor's `__get__` |
| Non-data descriptor | present | The instance value |
| Non-data descriptor | absent | Result of the descriptor's `__get__` |
| Plain value | present | The instance value |
| Plain value | absent | The class value |
| None | present | The instance value |
| None | absent | `AttributeError`, then `__getattr__` if defined |
Watching the order in action
This program puts all three kinds of class attribute next to matching instance entries.
class Data:
def __get__(self, obj, objtype=None):
return "data descriptor"
def __set__(self, obj, value):
print("__set__ called")
class NonData:
def __get__(self, obj, objtype=None):
return "non-data descriptor"
class A:
d = Data()
n = NonData()
plain = "class attribute"
def __getattr__(self, name):
return f"fallback for {name}"
a = A()
a.__dict__["d"] = "instance d"
a.__dict__["n"] = "instance n"
a.__dict__["plain"] = "instance plain"
print(a.d) # data descriptor
print(a.n) # instance n
print(a.plain) # instance plain
del a.__dict__["plain"]
print(a.plain) # class attribute
print(a.missing) # fallback for missingWriting directly into a.__dict__ is deliberate. Normal assignment would call Data.__set__ for d, and the instance entry would never exist. The next section covers that.
A pure-Python model
You can express steps 1 to 4 as a function. This is a simplified model of the real C implementation. It ignores __slots__ and the special handling of type objects.
_missing = object()
def find_in_mro(cls, name):
for base in cls.__mro__:
if name in vars(base):
return vars(base)[name]
return _missing
def lookup(obj, name):
cls = type(obj)
attr = find_in_mro(cls, name)
attr_type = type(attr)
is_data = (
attr is not _missing
and hasattr(attr_type, "__get__")
and (hasattr(attr_type, "__set__") or hasattr(attr_type, "__delete__"))
)
if is_data:
return attr_type.__get__(attr, obj, cls)
instance_dict = getattr(obj, "__dict__", {})
if name in instance_dict:
return instance_dict[name]
if attr is not _missing:
if hasattr(attr_type, "__get__"):
return attr_type.__get__(attr, obj, cls)
return attr
raise AttributeError(f"{cls.__name__!r} object has no attribute {name!r}")The model calls attr_type.__get__(attr, obj, cls) rather than attr.__get__(obj, cls). CPython looks up the descriptor methods on the type of the descriptor, so a __get__ stored in the descriptor object's own __dict__ is ignored.
Assignment follows a different path
Reading and writing are separate operations. obj.name = value calls type(obj).__setattr__, and object.__setattr__ does this:
- Find
namein the MRO. - If it is a descriptor whose type defines
__set__, call__set__(attr, obj, value). - Otherwise store
valueinobj.__dict__["name"].
A non-data descriptor never intercepts assignment. Assigning to the name creates an instance entry that shadows the descriptor from then on.
b = A()
b.d = 1 # prints: __set__ called
b.n = "assigned"
print(b.__dict__) # {'n': 'assigned'}
print(b.n) # assignedAfter b.d = 1, the instance __dict__ is still empty. The data descriptor consumed the assignment, so it alone decides where the value goes.
Edge cases
Descriptors must live on the class
Step 1 searches only the class hierarchy. A descriptor stored in an instance __dict__ is returned as a plain object, and its __get__ is never called.
class Probe:
def __get__(self, obj, objtype=None):
return "called"
class Holder:
pass
h = Holder()
h.probe = Probe()
print(type(h.probe).__name__) # Probe
Holder.probe = Probe()
print(Holder().probe) # calledInherited descriptors count
The MRO search finds descriptors defined on any base class. A subclass that sets a plain class attribute with the same name hides the base descriptor, because the subclass comes first in the MRO. The first match in MRO order is the only candidate considered.
The type of `attr` decides, not the instance
Python reads type(obj), not obj.__class__, when searching, so overriding __class__ on an instance does not redirect the search.
`AttributeError` inside a descriptor triggers `__getattr__`
Step 5 reacts to any AttributeError raised by __getattribute__. That includes one raised inside a descriptor's __get__. This can hide real bugs.
class Guarded:
def __getattr__(self, name):
return f"__getattr__({name})"
@property
def value(self):
raise AttributeError("inner failure")
print(Guarded().value) # __getattr__(value)The property exists and was found, but its failure message is lost because the fallback hook answered instead. Without __getattr__, the original AttributeError("inner failure") would reach you.
`__getattribute__` replaces the whole procedure
If a class defines its own __getattribute__, the steps above apply only if your version delegates to super().__getattribute__(name). A custom version that skips this call bypasses descriptors entirely. The fallback to __getattr__ still happens whenever your __getattribute__ raises AttributeError.
Predicting results quickly
To predict obj.name, ask these questions in order:
- Is
namein a class in the MRO? If so, does its type define__set__or__delete__? If yes, the descriptor wins. - Is
nameinobj.__dict__? If yes, that value wins. - Is
namein the class at all? If so, use it, applying__get__when present. - Otherwise fail, and let
__getattr__try.
Exercise
A class defines x = property(lambda self: "from property") with no setter. You run o = C(); o.__dict__["x"] = "from instance". What does o.x return, and what does o.x = 5 do?
Show answer
o.x returns "from property". A property is a data descriptor because it defines __set__ (and __delete__), so step 2 returns its __get__ result before the instance __dict__ is consulted. o.x = 5 raises AttributeError, because the property's __set__ runs and there is no setter function.
Exercise
A class defines __getattr__ and a property whose body contains the line raise AttributeError("boom"). Which value does obj.prop produce, and why is this a debugging hazard?
Show answer
It returns whatever __getattr__("prop") returns. The property's AttributeError is treated as a failed lookup, so Python calls the fallback hook. The original message "boom" is lost, which can make the real bug in the property body hard to find.