Sub topic 11
When lookup fails: __getattr__
This chapter assumes you know the lookup order from the previous chapters. object.__getattribute__ checks data descriptors, then the instance __dict__, then non-data descriptors and plain class attributes. Here you will see what happens when all of those fail.
What __getattr__ does
__getattr__ is a fallback hook. Python calls type(obj).__getattribute__(obj, name) first. If that raises AttributeError, Python then calls obj.__getattr__(name), but only if the class defines it. Whatever __getattr__ returns becomes the value of obj.name.
Because it runs last, __getattr__ never sees names that already exist. This differs from __getattribute__, which runs for every access.
A worked example
This class exposes dictionary keys as attributes.
class Config:
def __init__(self, data):
self._data = data
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(name)
try:
return self._data[name]
except KeyError:
raise AttributeError(
f"{type(self).__name__!r} object has no attribute {name!r}"
) from None
c = Config({"host": "localhost"})
print(c.host) # localhost
print(getattr(c, "port", None)) # None
print(hasattr(c, "port")) # FalseThe method ends with AttributeError for unknown names on purpose. hasattr and the three-argument getattr rely on that exception. If you raised KeyError instead, they would crash.
Pitfalls
Infinite recursion
self._data is an ordinary lookup. If _data is not in the instance __dict__, Python calls __getattr__("_data"), which reads self._data again, and so on. This happens when an object is created without __init__, as in copy and pickle. The startswith("_") guard above stops the loop.
Hidden errors from properties
An AttributeError raised inside a property getter looks to Python like a failed lookup of the property itself. Python then calls __getattr__, which can hide the real bug.
class Broken:
@property
def value(self):
raise AttributeError("real problem inside the getter")
def __getattr__(self, name):
return f"fallback for {name}"
print(Broken().value) # fallback for valueThe message "real problem inside the getter" is lost. Keep __getattr__ narrow and re-raise for names you do not handle.
Special methods bypass it
Operations such as len(obj) and obj + 1 look up __len__ and __add__ on the type, not through the instance. A __getattr__ on the class does not provide them. A proxy has to define each special method it wants to forward.
Choosing between the hooks
| Hook | Runs | Typical use |
|---|---|---|
| `__getattribute__` | On every access | Logging or blocking all reads. Easy to break with recursion. |
| `__getattr__` | Only after lookup fails | Dynamic attributes, proxies, delegation |
| Descriptor `__get__` | When the attribute is found on the class | Per-attribute behavior such as validation or computed values |
Prefer a descriptor when the attribute names are known in advance. Use __getattr__ when the names are only known at runtime.
Exercise
A class defines __getattr__ that returns the string "default" for any name. Given obj = Cls() and obj.x = 5, what do obj.x and obj.y return, and is __getattr__ called for each?
Show answer
obj.x returns 5 and __getattr__ is not called, because x is found in the instance __dict__ by normal lookup. obj.y fails normal lookup, so __getattr__("y") is called and returns "default".