Sub topic 3
What obj.name actually calls
This chapter assumes you can write classes, know that instances and classes each have a __dict__, and have seen dunder methods such as __init__. The previous chapters covered where attributes are stored and how the MRO orders the class hierarchy. This chapter covers the code that performs the search.
The expression is a method call
Reading obj.name is not a built-in dictionary access. Python looks up __getattribute__ on the type of obj and calls it with the instance and the attribute name as a string. For most classes that method is object.__getattribute__, which implements the full search.
class A:
x = 1
a = A()
a.y = 2
print(a.y)
print(type(a).__getattribute__(a, "y"))
print(object.__getattribute__(a, "y"))
print(getattr(a, "y"))All four lines print 2. The built-in getattr(a, "y") takes the same route. It is the form to use when the name is only known at runtime.
The related operations follow the same pattern. Each one is handed to a hook on the type.
| Operation | Hook called on `type(obj)` | Default implementation |
|---|---|---|
| `obj.name` | `__getattribute__(obj, "name")` | `object.__getattribute__` |
| `obj.name = v` | `__setattr__(obj, "name", v)` | `object.__setattr__` |
| `del obj.name` | `__delattr__(obj, "name")` | `object.__delattr__` |
| `obj.name` after an `AttributeError` | `__getattr__(obj, "name")` | not defined by default |
__getattr__ differs from the other three. object does not define it, and Python calls it only as a fallback. The section on the fallback hook below covers it.
What the default implementation does
object.__getattribute__ performs the search that later chapters examine step by step. In outline:
- Search the MRO of
type(obj)forname. - If the result is a data descriptor, call its
__get__and return the result. - Otherwise, if
nameis inobj.__dict__, return that value. - Otherwise, if step 1 found something, return it. If it is a non-data descriptor, call its
__get__first. - Otherwise, raise
AttributeError.
The order of steps 2 and 3 is what makes descriptors interesting. The next two chapters define the terms and work through the order in detail. For now, remember that the class is consulted before the instance, even though the instance's __dict__ is checked first in a casual mental model.
The hook is found on the type, not the instance
Python finds __getattribute__ by searching type(obj), not by running obj.__getattribute__. Doing it the second way would need a lookup to perform the lookup. A practical consequence is that assigning a hook on one instance does nothing.
class P:
def __getattribute__(self, name):
return "class hook"
p = P()
p.__getattribute__ = lambda name: "instance hook"
print(p.x) # class hookThe assignment succeeds and stores a lambda in the instance __dict__. The implicit call still goes to the class, so the lambda is never used.
The same rule applies to operators and built-ins. len(obj), obj[i], obj + other and for x in obj use the special method found on the type and skip __getattribute__ entirely.
class L:
def __getattribute__(self, name):
print("hook", name)
return super().__getattribute__(name)
def __len__(self):
return 3
l = L()
print(len(l)) # 3, with no "hook" line
print(l.__len__()) # hook __len__, then 3Calling len(l) prints only 3. Calling l.__len__() is an ordinary attribute read, so the hook runs. This is why overriding __getattribute__ cannot intercept implicit special-method calls. It is also why a proxy class has to define each special method it wants to forward.
Overriding `__getattribute__`
You can replace the hook to observe or control every read. Delegate to super().__getattribute__(name) for the normal behavior.
class Traced:
def __init__(self):
self.value = 10
def __getattribute__(self, name):
print(f"looking up {name!r}")
return super().__getattribute__(name)
t = Traced()
print(t.value)
print(t.__class__)This prints looking up 'value' and 10, then looking up '__class__' and <class '__main__.Traced'>. Notice that even __class__ goes through the hook. Method calls such as t.method() do as well, because the method is looked up first and called second.
Inside the hook you must not read attributes of self with normal syntax. Doing so calls the hook again.
class Bad:
def __getattribute__(self, name):
return self.__dict__[name] # reads self.__dict__, which calls this hook
try:
Bad().x
except RecursionError:
print("RecursionError")Reading self.__dict__ triggers __getattribute__("__dict__"), which reads self.__dict__, and so on. The fix is to go through object.__getattribute__(self, "__dict__") or super().__getattribute__.
The fallback hook: `__getattr__`
__getattr__ is called only after __getattribute__ has raised AttributeError. Names that exist are never routed to it.
class F:
def __getattr__(self, name):
print(f"fallback for {name!r}")
return 0
f = F()
f.a = 5
print(f.a) # 5
print(f.b) # fallback for 'b', then 0The mechanism is the AttributeError, not a check for existence. If a descriptor's __get__ or a property getter raises AttributeError for some other reason, Python treats it as a failed lookup and calls __getattr__. A bug inside the getter can then surface as a confusing fallback result or a misleading error message. Raise other exception types for real errors inside descriptors and properties.
Because the fallback needs the same AttributeError signal, hasattr(obj, name) and getattr(obj, name, default) work by catching that exception. They return False or the default when the hook raises it, including after __getattr__ has also failed.
Writes and deletes
Assignment and deletion have their own hooks. object.__setattr__ also consults the type first. If the class has a descriptor with __set__ under that name, the descriptor handles the write. Otherwise, the value goes into the instance __dict__. Later chapters cover this in detail. The practical rule for overriding __setattr__ mirrors the one for reads: store values by calling super().__setattr__(name, value), never by assigning self.name = value inside the hook.
class Logged:
def __setattr__(self, name, value):
print(f"set {name!r} = {value!r}")
super().__setattr__(name, value)
obj = Logged()
obj.size = 4 # set 'size' = 4
print(obj.size) # 4There is no __getattr__ counterpart for writes. __setattr__ is always called, not only on failure.
Reading attributes on a class
When the object is itself a class, as in C.name, the same rule applies one level up. Python calls type(C).__getattribute__(C, "name"). For ordinary classes, type(C) is type, so the method is type.__getattribute__. It searches the class and its bases, not the metaclass first. The last chapters cover this and the effect of metaclasses.
class C:
x = 1
print(type(C)) # <class 'type'>
print(type.__getattribute__(C, "x")) # 1
print(type(C).__getattribute__ is object.__getattribute__) # FalseThe two methods are different functions, which is why C.name and C().name can behave differently for the same descriptor.
Summary of the model
obj.namecallstype(obj).__getattribute__(obj, "name").- The hook is found on the type, so instance-level replacements are ignored and implicit special-method calls bypass it.
object.__getattribute__consults the class MRO, then the instance__dict__, and applies descriptor rules between them.__getattr__runs only after anAttributeError.- Inside custom hooks, delegate to
super()orobjectto avoid infinite recursion.
Exercise
A class defines both __getattribute__ (which always delegates to super().__getattribute__(name)) and __getattr__. Code reads obj.missing, where missing is not defined anywhere. In what order do the two methods run, and what happens if __getattr__ also raises AttributeError?
Show answer
__getattribute__ runs first and its super() call raises AttributeError because the name is not found. Python then calls __getattr__(obj, "missing"). If that also raises AttributeError, the exception propagates to the caller of obj.missing. getattr(obj, "missing", default) returns the default and hasattr returns False.
Exercise
You define __len__ on a class and also install obj.__len__ = lambda: 99 on one instance. What does len(obj) return, and what does obj.__len__() return? Why?
Show answer
len(obj) returns the value from the class-level __len__, because built-ins find special methods on type(obj) and ignore the instance __dict__. obj.__len__() is an ordinary attribute read. The instance entry lambda: 99 is found, since a plain function in the class is a non-data descriptor and the instance __dict__ takes precedence over it. So it returns 99.