Sub topic 15
Dynamic attribute access with __getattr__
This chapter assumes you can write classes with instance attributes, know that instances store attributes in __dict__, and have read the earlier chapters on special methods. By the end you will know when Python calls __getattr__, how it differs from __getattribute__, and how to avoid the infinite-recursion and silent-failure traps.
How attribute lookup works
When you write obj.name, Python calls type(obj).__getattribute__(obj, 'name'). The default implementation, object.__getattribute__, searches in this order:
- A data descriptor on the class (for example a
property). - The instance's
__dict__. - A non-data descriptor or plain attribute on the class (for example a method).
If that search raises AttributeError, Python then calls __getattr__(obj, 'name'), but only if the class defines it. __getattr__ is a fallback for names that were not found.
The hooks at a glance
| Method | Called when | Typical use |
|---|---|---|
| `__getattr__(self, name)` | Normal lookup failed | Computed or delegated attributes |
| `__getattribute__(self, name)` | Every attribute read | Tracing, access control (rare) |
| `__setattr__(self, name, value)` | Every attribute assignment | Validation, read-only objects |
| `__delattr__(self, name)` | `del obj.name` | Blocking or tracking deletion |
| `__dir__(self)` | `dir(obj)` | Advertising dynamic names |
A first example: attributes backed by a dict
The class below exposes dictionary keys as attributes.
class Config:
def __init__(self, data):
self._data = dict(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
def __dir__(self):
return sorted(set(super().__dir__()) | set(self._data))
cfg = Config({'host': 'localhost', 'port': 8080})
print(cfg.host) # localhost
print(cfg.port) # 8080
print(hasattr(cfg, 'timeout')) # False
print(getattr(cfg, 'timeout', 30)) # 30
print('host' in dir(cfg)) # TrueThree details matter here.
- The method raises
AttributeErrorfor unknown names.hasattr()andgetattr(obj, name, default)depend on that exception. If you raisedKeyErrorinstead, both would break. self._datais a normal attribute found in__dict__.__getattr__never runs for it, as long as__init__has run.- The underscore guard prevents recursion. It is explained next.
The recursion trap
Suppose Config.__getattr__ had no underscore guard, and an instance is created without running __init__. That happens in copy.copy() and pickle, which build an empty instance first. The first lookup of self._data fails, so Python calls __getattr__('_data'). That method reads self._data again, which calls __getattr__('_data') again, and so on until RecursionError.
The guard if name.startswith('_') fixes it. Copying now works:
import copy
cfg = Config({'host': 'localhost'})
clone = copy.copy(cfg)
print(clone.host) # localhostDelegation: wrapping another object
__getattr__ is well suited to proxies, because only the names the wrapper does not define are forwarded.
class LoggingProxy:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError(name)
value = getattr(self._target, name)
if not callable(value):
return value
def wrapper(*args, **kwargs):
print(f'calling {name} with {args}')
return value(*args, **kwargs)
return wrapper
proxy = LoggingProxy([3, 1, 2])
proxy.append(4) # calling append with (4,)
proxy.sort() # calling sort with ()
print(proxy._target) # [1, 2, 3, 4]
try:
len(proxy)
except TypeError as e:
print(e) # object of type 'LoggingProxy' has no len()The last lines show an important limit. Implicit special-method calls such as len(proxy), proxy + x or for x in proxy look the method up on the type, not the instance. They skip both __getattr__ and __getattribute__. To make a proxy support len(), you must define __len__ on the proxy class. proxy.__len__() called explicitly would work through __getattr__, but len(proxy) would not.
Controlling writes: __setattr__ and __delattr__
__setattr__ runs for every assignment, including the ones inside __init__. To store a value without triggering your own hook, call object.__setattr__.
class ReadOnly:
def __init__(self, **fields):
for name, value in fields.items():
object.__setattr__(self, name, value)
def __setattr__(self, name, value):
raise AttributeError(f'cannot set {name!r}: instance is read-only')
def __delattr__(self, name):
raise AttributeError(f'cannot delete {name!r}: instance is read-only')
point = ReadOnly(x=1, y=2)
print(point.x) # 1
try:
point.x = 5
except AttributeError as e:
print(e) # cannot set 'x': instance is read-onlyWriting self.x = value inside __setattr__ calls __setattr__ again and recurses forever. Always delegate to object.__setattr__(self, name, value) or super().__setattr__(name, value).
For simple read-only objects, __slots__ with a frozen dataclass or a named tuple is usually clearer. Use __setattr__ when you need custom rules, such as validating certain names and allowing others.
__getattribute__: the heavy hook
__getattribute__ intercepts every read, including reads of attributes that exist. That makes it easy to break the object. Use super().__getattribute__ to get the normal behavior.
class Traced:
def __init__(self):
self.value = 42
def __getattribute__(self, name):
if not name.startswith('__'):
print(f'reading {name}')
return super().__getattribute__(name)
t = Traced()
print(t.value)
# reading value
# 42Writing self.something inside __getattribute__ triggers a second call to __getattribute__, which is the same recursion as before. Prefer __getattr__ unless you truly need to see every access. It is cheaper, because it only runs on failure, and it is much harder to get wrong.
Common errors
- Raising the wrong exception.
__getattr__must raiseAttributeErrorfor unknown names. ReturningNoneinstead makes every misspelled attribute look valid and hides bugs. - Masked errors in properties. If a property getter raises
AttributeErrorinternally, Python treats it as a failed lookup and falls through to__getattr__. The real error disappears:
class Box:
@property
def size(self):
return self._size # typo: _size was never set
def __getattr__(self, name):
return f'fallback for {name}'
print(Box().size) # fallback for _sizeA guard on underscore names, as in Config, would have surfaced the real problem.
- Expecting dunder lookups to be intercepted. As shown with
len(proxy), operators and built-ins bypass__getattr__. - Breaking tooling. Code that accepts any name makes autocompletion, static type checkers and
dir()less useful. Implement__dir__and, for typed code, declare the expected attributes in annotations. - Surprising
hasattr. If__getattr__accepts every name,hasattr(obj, 'anything')is alwaysTrue. Duck-typing checks such ashasattr(obj, 'read')then give wrong answers.
When to use it
Use __getattr__ for delegation, lazily computed attributes, and thin wrappers over data such as JSON or configuration. For a fixed set of known attributes that need validation or computation, use property or a descriptor, covered in the next chapter. They are explicit, visible to tools, and run only for the names you choose.
Exercise
A class defines __getattr__(self, name) that returns self.defaults[name], and defaults is assigned in __init__. Calling copy.copy(obj) raises RecursionError. Why, and what is the smallest fix?
Show answer
copy.copy creates a new instance without calling __init__, so defaults is not in the new instance's __dict__. Looking up self.defaults fails and calls __getattr__('defaults'), which looks up self.defaults again, forever. The smallest fix is to raise AttributeError at the top of __getattr__ for names that start with an underscore or equal 'defaults', or to read it with self.__dict__.get('defaults', {}).
Exercise
Why does len(proxy) fail for a proxy that forwards unknown attributes with __getattr__, even though proxy.__len__() works? How do you fix it?
Show answer
Built-in functions and operators find special methods by looking on type(proxy), skipping the instance and __getattr__. proxy.__len__() is an ordinary attribute access, so it goes through __getattr__. The fix is to define __len__ on the proxy class, for example def __len__(self): return len(self._target).
Exercise
What is wrong with this method, and what does it do when obj.x = 1 runs?
def _setattr(self, name, value):
self.dict_[name] = value
print('set', name)
Show answer
Nothing is wrong with the recursion side: writing into self.__dict__ directly does not call __setattr__ again, so it works. It stores x and prints set x. The version that fails is self.x = value inside the method, which would recurse forever. For classes that use __slots__ there is no __dict__, so super().__setattr__(name, value) is the safer form.