Sub topic 11
When lookup fails: __getattr__
This chapter assumes you know how object.__getattribute__ walks the lookup order: data descriptor, instance __dict__, then non-data descriptor or class attribute. Here we cover what happens when every step of that order comes up empty, and the cases where it fires when you did not expect it.
Where __getattr__ fits
__getattr__ is a fallback hook. Python calls it only after the normal lookup has raised AttributeError. It is not part of the descriptor-aware search itself.
The sequence for obj.name on a class that defines __getattr__ is:
- Python calls
type(obj).__getattribute__(obj, "name"). For most classes that isobject.__getattribute__. - If that returns a value, the process ends.
__getattr__is never called. - If it raises
AttributeError, Python callstype(obj).__getattr__(obj, "name"). - Whatever
__getattr__returns becomes the result. If it raises, that exception propagates to the caller.
Python looks up __getattr__ on the type, as it does for other special methods. Assigning obj.__getattr__ = some_function on a single instance has no effect on obj.name.
A basic fallback
This class stores real values in its __dict__. Names it does not know about are handled by the hook.
class Config:
def __init__(self, **values):
self.__dict__.update(values)
def __getattr__(self, name):
print(f"__getattr__ called for {name!r}")
raise AttributeError(
f"{type(self).__name__!r} object has no attribute {name!r}"
)
c = Config(host="localhost")
print(c.host) # localhost (hook not called)
print(hasattr(c, "port")) # prints the hook message, then Falsec.host is found in the instance __dict__, so the hook stays silent. hasattr(c, "port") triggers the hook, and the AttributeError it raises is what makes hasattr return False.
If you return a default such as None for every unknown name, hasattr becomes True for every name. Library code that probes for optional methods, such as __iter__-style checks, will then misbehave. Raise AttributeError for names you do not handle.
Contrast with __getattribute__
The two hooks differ in when they run and what they replace.
| Aspect | `__getattribute__` | `__getattr__` |
|---|---|---|
| When it runs | On every attribute access | Only after normal lookup raised `AttributeError` |
| Default implementation | `object.__getattribute__` | None. Not defined on `object` |
| Replaces descriptor handling | Yes, if you do not call `super()` | No |
| Typical use | Logging, access control, proxies | Defaults, delegation, dynamic attributes |
| Recursion risk | High | Moderate |
If you override __getattribute__, you take over the whole lookup order, including descriptor handling. Delegate to super().__getattribute__(name) unless you intend to replace that behavior. If your __getattribute__ raises AttributeError, Python still calls __getattr__ afterward.
class Traced:
def __getattribute__(self, name):
print(f"lookup {name}")
return super().__getattribute__(name)
def __getattr__(self, name):
return f"<missing {name}>"
t = Traced()
t.x = 1
print(t.x) # lookup x, then 1
print(t.y) # lookup y, then <missing y>Assignment does not go through either hook. t.x = 1 uses __setattr__, which has no fallback counterpart.
Descriptors that raise AttributeError
A descriptor's __get__ runs inside step 1 of the sequence above. If it raises AttributeError, Python treats the whole lookup as failed and calls __getattr__. A property getter is a descriptor __get__, so this applies to properties too.
This can hide bugs. An AttributeError raised from deep inside a getter, for example from a typo, is swallowed by the fallback. If the hook then raises its own error, the message talks about the property name and not the real mistake.
class Report:
def __init__(self, data):
self.data = data
@property
def total(self):
return sum(self.dat) # typo: should be self.data
def __getattr__(self, name):
print(f"__getattr__({name!r})")
raise AttributeError(
f"{type(self).__name__!r} object has no attribute {name!r}"
)
r = Report([1, 2, 3])
try:
r.total
except AttributeError as e:
print(e)The output is:
__getattr__('dat')
__getattr__('total')
'Report' object has no attribute 'total'The typo on self.dat triggers the hook once. The failed getter then triggers it a second time for total. The final message says total does not exist, even though total is defined on the class. When you see this message for an attribute you know is defined, check for a hidden AttributeError inside a property or descriptor.
Delegation and the recursion trap
The most common legitimate use of __getattr__ is delegation: forwarding unknown names to a wrapped object.
import copy
class Proxy:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
if name == "_target":
raise AttributeError(name)
return getattr(self._target, name)
p = Proxy([3, 1, 2])
print(p.count(1)) # 1
q = copy.copy(p)
print(q._target is p._target) # True
try:
len(p)
except TypeError as e:
print(e) # object of type 'Proxy' has no len()The _target guard matters. copy.copy builds a new Proxy without calling __init__, then probes it for __setstate__. At that moment the new object has no _target in its __dict__. Without the guard, the sequence is:
__getattr__("__setstate__")runs and readsself._target._targetis missing, so Python calls__getattr__("_target").- That call reads
self._targetagain, and the cycle repeats untilRecursionError.
Raising AttributeError for the attribute the hook itself depends on stops the cycle. The same problem appears with pickle, which also creates instances without __init__.
The last two lines show a second limit. len(p) fails even though p.__len__() would succeed. Implicit special-method calls such as len(), +, with and iteration look the method up on the type, skipping both the instance and __getattr__. A proxy must define the special methods it wants to support, or generate them on the class.
What __getattr__ does not do
- It does not run for names found by the normal lookup, including class attributes and descriptors that return successfully.
- It does not run for attribute assignment or deletion. Those use
__setattr__and__delattr__. - It does not run for implicit special-method lookups on the type.
- It does not run for lookups on the class itself, such as
Proxy.something. Those go throughtype.__getattribute__, so a hook for class-level fallback belongs on the metaclass.
Pitfalls summary
| Symptom | Likely cause | Fix |
|---|---|---|
| `RecursionError` inside `__getattr__` | The hook reads an attribute that may be missing, such as `self._target` before `__init__` | Guard that name, or use `object.__getattribute__` |
| `hasattr` is always `True` | The hook returns a default instead of raising | Raise `AttributeError` for unknown names |
| Property error message names the wrong attribute | An inner `AttributeError` fell through to the hook | Run the getter directly, or remove the hook while debugging |
| `len(proxy)` or `proxy + 1` fails | Special methods are looked up on the type | Define them on the class |
| Hook seems slow | It runs after a full failed lookup | Cache the result in `__dict__` or on the class |
Exercise
A class defines __getattr__ that returns the string "unknown" for every name. What does hasattr(obj, "anything") return, and why is that usually a bug?
Show answer
It returns True, because __getattr__ returns a value instead of raising AttributeError. Code that probes for optional attributes will wrongly conclude they exist. The hook should raise AttributeError for names it does not handle.
Exercise
In the Report example, total is a property defined on the class, yet r.total ends with the message "'Report' object has no attribute 'total'". Explain the sequence that produces it.
Show answer
The property getter runs inside object.__getattribute__. It reads self.dat, which does not exist, so __getattr__("dat") is called and raises AttributeError. That error leaves the getter, so the lookup of total counts as failed. Python then calls __getattr__("total"), which raises the message about total.
Exercise
Why can p.__len__() work on the Proxy class while len(p) raises TypeError?
Show answer
The explicit call p.__len__ goes through normal attribute lookup, fails on Proxy, and falls back to __getattr__, which forwards it to the wrapped list. The len() function looks up __len__ on type(p) directly, skipping the instance and __getattr__. Proxy has no __len__, so it raises TypeError.