Sub topic 3
What obj.name actually calls
This chapter assumes you can write Python classes, know the difference between instance and class attributes, and have seen special (dunder) methods. It also builds on the earlier chapters about __dict__ and the method resolution order (MRO).
Attribute access is a method call
The expression obj.name is not a direct dictionary read. Python turns it into a call on the object's type:
type(obj).__getattribute__(obj, "name")Almost every class inherits object.__getattribute__. That method holds the lookup rules: it searches the class MRO and the instance __dict__. The next chapters cover the descriptor protocol, which is the part of those rules that decides precedence. For now, treat __getattribute__ as the single entry point for reading an attribute.
The built-in getattr(obj, "name") goes through the same entry point. The only difference is that the name is a string you computed at run time.
Watching the hook run
Override __getattribute__ to see every read. Delegate to super() for the real work. If you wrote self.name inside the method, it would call itself forever.
class Traced:
def __init__(self):
self.x = 1
def __getattribute__(self, name):
print(f"__getattribute__({name!r})")
return super().__getattribute__(name)
def __getattr__(self, name):
print(f"__getattr__({name!r})")
return "fallback"
t = Traced()
print(t.x)
print(t.y)Running it prints:
__getattribute__('x')
1
__getattribute__('y')
__getattr__('y')
fallbackReading t.x calls only __getattribute__. Reading t.y calls __getattribute__ first. It fails because y exists nowhere, so Python then calls __getattr__.
The two hooks
The two methods have different jobs, and people often confuse them.
| Method | When Python calls it | Typical use |
|---|---|---|
| `__getattribute__` | On every attribute read | Rarely overridden. Logging or proxies. |
| `__getattr__` | Only after `__getattribute__` raised `AttributeError` | Default values, delegation to another object |
__getattr__ is a fallback only. If you define it and also have a normal attribute with that name, the normal attribute wins and __getattr__ never runs.
Details that matter
- The lookup starts at the type. Python finds
__getattribute__ontype(obj), not on the instance. Assigningobj.__getattribute__ = somethinghas no effect onobj.name. - Implicit special-method calls skip it.
len(obj)andobj + 1look up__len__and__add__on the type directly. They do not go throughobj.__getattribute__. Explicitobj.__len__does. - Only reads are covered. Assignment goes through
__setattr__and deletion through__delattr__. The descriptor__set__and__delete__methods hook into those.
Common errors
- Overriding
__getattribute__when__getattr__is enough. The override runs on every access and slows down all of them. - Raising something other than
AttributeErrorfrom__getattribute__. Then__getattr__is never called, andhasattrpropagates the error instead of returningFalse. - Returning a value from
__getattr__for every name. Tools such ascopyandpickleprobe for special names like__deepcopy__, and a catch-all fallback can break them.
Exercise
Given a class that defines both __getattribute__ (delegating to super()) and __getattr__, and an instance t with no attribute z, which methods run, and in what order, when you evaluate t.z? What changes if t.__dict__ contains "z"?
Show answer
__getattribute__('z') runs first, raises AttributeError, and then __getattr__('z') runs and its result is returned. If t.__dict__ contains "z", __getattribute__ finds it and returns it, so __getattr__ is never called.