Python Reference ยท Classes and Special Methods
__getattr__() and __getattribute__()
Reference for Python __getattr__ and __getattribute__: attribute lookup order, dynamic attributes, proxies, infinite recursion and __setattr__ and __delattr__.
Two special methods let a class take part in attribute lookup. __getattribute__() is called for every attribute access on an instance. __getattr__() is a fallback: Python calls it only when the normal lookup fails and raises AttributeError.
__getattr__() is the one you will normally want: it supports dynamic attributes, proxies and wrappers, and default values. __getattribute__() is powerful but easy to get wrong, because it intercepts even your own self.x accesses.
class Dynamic: def __getattr__(self, name): return f"<{name}?>" print(Dynamic().color) # <color?>
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class C: def __getattr__(self, name): ... # fallback def __getattribute__(self, name): ... # every access def __setattr__(self, name, value): ... # every assignment def __delattr__(self, name): ... # every deletion
| Method | Called |
|---|---|
__getattribute__(name) |
On every attribute read, before anything else. |
__getattr__(name) |
Only if the normal lookup (instance dict, class, parents, descriptors) raised AttributeError. |
__setattr__(name, value) |
On every assignment obj.name = value. |
__delattr__(name) |
On del obj.name. |
Return value: the attribute value (for the getters). The setter and deleter return None.
Raises: AttributeError when the attribute does not exist. Raising it from __getattr__() is what makes getattr(obj, name, default) and hasattr() work correctly.
Usage notes
- Order of lookup. Data descriptors (like properties) come first, then the instance
__dict__, then class attributes, then__getattr__().__getattribute__()wraps the whole process. - Avoid infinite recursion. Inside
__getattribute__()and__setattr__(), reach the real storage throughobject.__getattribute__(self, name)orsuper().__setattr__(), neverself.name. In__getattr__(), touching a missing attribute (likeself.otherabove) recurses forever. - Guard names that may not exist yet. During
copyandpicklethe object is rebuilt without__init__, soself._targetmay be missing and__getattr__()is called for_targetitself. RaiseAttributeErrorfor such names. - Raise
AttributeError, notKeyError, for unknown names, otherwisehasattr()andgetattr()with a default misbehave. - Special methods bypass these hooks. Implicit calls like
len(obj)orobj + 1look up methods on the type, so a proxy must define them explicitly. - Performance.
__getattribute__()slows every access;__getattr__()costs only on misses. - Alternatives.
@propertyfor a few known computed attributes,__slots__or dataclasses for structure,__dir__()to advertise dynamic names todir(). - Module level. A module may define
__getattr__(name)too (Python 3.7+), useful for lazy imports and deprecation warnings.