Sub topic 15
Dynamic attribute access with __getattr__
This chapter assumes you can define classes, know that instances store attributes in a __dict__, and have read the chapters on __repr__ and __eq__. Here you will learn how Python looks up attributes and how __getattr__ and __setattr__ let you change that lookup.
How attribute lookup works
When you write obj.name, Python calls type(obj).__getattribute__(obj, 'name'). The default version checks data descriptors on the class, then the instance __dict__, then non-data descriptors and class attributes. If all of that fails with AttributeError, Python calls __getattr__(self, name), if the class defines it.
So __getattr__ is a fallback. It runs only for attributes that were not found normally.
A forwarding wrapper
A common use is delegation: an object passes unknown attribute requests to another object.
class Logged:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
print(f'looking up {name}')
return getattr(self._target, name)
items = Logged([3, 1, 2])
items.sort() # looking up sort
print(items._target) # [1, 2, 3]
print(items.count(2)) # looking up count, then 1_target is found in the instance __dict__, so __getattr__ is not called for it.
Raise AttributeError for unknown names
When your __getattr__ cannot supply a value, raise AttributeError. Returning None instead makes every misspelled name look valid. It also breaks hasattr() and getattr(obj, name, default), which rely on AttributeError.
class Config:
def __init__(self, **values):
self._values = values
def __getattr__(self, name):
try:
return self._values[name]
except KeyError:
raise AttributeError(
f'{type(self).__name__!r} object has no attribute {name!r}'
) from None
cfg = Config(host='localhost', port=8080)
print(cfg.port) # 8080
print(hasattr(cfg, 'debug')) # FalseThe recursion trap
__getattr__ itself reads attributes. If self._values is missing, for example while unpickling or copying an object before __init__ has run, the lookup of _values calls __getattr__ again, and so on until RecursionError.
Guard against it by refusing private names, or by reading through object.__getattribute__:
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError(name)
return self._values[name]__setattr__
__setattr__(self, name, value) runs on every assignment, including those in __init__. Unlike __getattr__, it is not a fallback. Inside it, call super().__setattr__(name, value). Writing self.name = value would call __setattr__ again and recurse forever.
class Frozen:
def __init__(self, x):
super().__setattr__('x', x)
def __setattr__(self, name, value):
raise AttributeError('instances are read-only')
f = Frozen(5)
print(f.x) # 5
try:
f.x = 6
except AttributeError as e:
print(e) # instances are read-onlyCommon errors
| Mistake | Result |
|---|---|
| Returning `None` for unknown names | `hasattr()` is always true and typos pass silently |
| Using `self.x` in `__getattr__` before `x` is set | `RecursionError` |
| Assigning `self.name = value` inside `__setattr__` | `RecursionError` |
| Expecting `__getattr__` to catch `len(obj)` or `obj + 1` | Not called, because special methods are looked up on the type |
Exercise
A class defines __getattr__ that returns 42 for any name. What does hasattr(obj, 'anything') return, and why is this usually a bug?
Show answer
It returns True, because __getattr__ never raises AttributeError. Misspelled attribute names then silently succeed with 42, and code that uses hasattr to detect missing features gets wrong answers. The method should raise AttributeError for names it does not support.
Exercise
Why does self.count = 0 inside a custom __setattr__ cause a RecursionError, and how do you fix it?
Show answer
The assignment calls __setattr__ again, which runs the same assignment. Fix it by calling super().__setattr__('count', 0) (or object.__setattr__(self, 'count', 0)) so the default storage logic runs.