Python __getattr__ Method
Last modified November 17, 2026 Python 3.15
__getattr__ is a fallback: Python calls it only when normal
lookup has failed. That makes it useful for computed names, lazy values, and
proxies without affecting attributes that already exist. This article shows
the failure path, dynamic methods, lazy loading, forwarding, and how to pair
the hook with __dir__.
A fallback for missing names
When obj.name cannot be found, Python calls
__getattr__(obj, 'name'). The hook should return a value or raise
AttributeError. Raising that exception for unknown names matters
because tools such as hasattr rely on it.
class Dynamic:
def __getattr__(self, name):
print("__getattr__", name)
if name == "color":
return "blue"
raise AttributeError(f"no attribute {name!r}")
obj = Dynamic()
print(obj.color)
try:
print(obj.size)
except AttributeError as e:
print(type(e).__name__, e)
The colour is supplied by the hook, while size is not and produces an
AttributeError. The printed lines show the hook running for both
names; the exception is caught so the example can continue.
$ python basic_getattr.py __getattr__ color blue __getattr__ size AttributeError no attribute 'size'
Normal lookup wins
Because __getattr__ runs only after a failed lookup, real
instance attributes are never affected. The hook stays quiet when the name
already exists.
class Tracked:
def __init__(self):
self.real = "stored"
def __getattr__(self, name):
print("fallback", name)
return "computed"
obj = Tracked()
print(obj.real)
print(obj.missing)
print("missing" in obj.__dict__)
Reading real prints only the stored value; no fallback message
appears. Reading missing triggers the hook, and the final line
confirms that nothing was added to the instance dictionary. The fallback
therefore leaves ordinary state untouched.
$ python normal_lookup.py stored fallback missing computed False
Creating methods on demand
The hook can return a callable when a name follows a pattern. This is a common way to expose an API whose method names are only known at runtime.
class Calculator:
def __getattr__(self, name):
if name.startswith("calc_"):
operation = name[5:]
def calculate(*args):
return f"{operation}{args}"
return calculate
raise AttributeError(name)
c = Calculator()
print(c.calc_sum(1, 2, 3))
print(c.calc_product(4, 5))
Names beginning with calc_ produce a function whose output
depends on the suffix. Each access returns a fresh closure; the class does not
store these methods anywhere. An unrecognised name would raise
AttributeError.
$ python dynamic_methods.py sum(1, 2, 3) product(4, 5)
Lazy loading
A lazy attribute is loaded on first use and then cached. The hook checks its cache before doing work, so the expensive step happens at most once per name.
class Lazy:
def __init__(self):
self._cache = {}
def __getattr__(self, name):
if name not in self._cache:
print(f"Loading {name}...")
self._cache[name] = f"value of {name}"
return self._cache[name]
loader = Lazy()
print(loader.data1)
print(loader.data1)
The loading message is printed once. The second read skips the work and
returns the cached value. Because the value lives in _cache
rather than as an instance attribute, the hook is still called on the second
access, but it does no loading.
$ python lazy_loading.py Loading data1... value of data1 value of data1
Forwarding to another object
A proxy can forward unknown attributes to a wrapped object. Since
__getattr__ only sees names the proxy does not define, attributes
such as _target continue to work normally.
class Proxy:
def __init__(self, target):
self._target = target
def __getattr__(self, name):
print("forward", name)
return getattr(self._target, name)
class Target:
def __init__(self, value):
self.value = value
def doubled(self):
return self.value * 2
p = Proxy(Target(21))
print(p.value)
print(p.doubled())
Both value and doubled are forwarded to the target,
and the printed lines show when that happens. This pattern underlies wrappers,
lazy remote objects, and mock objects; adding logging around the forward is
straightforward.
$ python proxy_pattern.py forward value 21 forward doubled 42
Introspection with __dir__
Dynamic attributes do not appear in dir() unless the class says
so. Overriding __dir__ to list the available names keeps
introspection and autocompletion useful.
class Config:
def __init__(self, data):
self._data = data
def __getattr__(self, name):
if name in self._data:
return self._data[name]
raise AttributeError(name)
def __dir__(self):
return sorted(self._data)
c = Config({"name": "Alice", "age": 30, "city": "London"})
print(c.name)
print(c.age)
print([n for n in dir(c) if not n.startswith("_")])
try:
print(c.missing)
except AttributeError as e:
print(type(e).__name__, e)
The keys of the wrapped dictionary are exposed as attributes and also
appear in the filtered dir() output. Looking up an absent name
still raises AttributeError. Pairing __dir__ with
__getattr__ is good practice when names are generated at
runtime.
$ python dict_access.py Alice 30 ['age', 'city', 'name'] AttributeError missing
Best practices
A fallback hook should stay predictable:
- Raise
AttributeErrorfor names you do not provide. - Keep the logic simple; a complex hook is hard to debug.
- Document which dynamic names are available.
- Pair the hook with
__dir__so introspection sees them. - Remember the hook is skipped for attributes that already exist.
Source
object.__getattr__ - Python documentation
Customizing attribute access - Python documentation
object.__dir__ - Python documentation
In this article we have implemented the __getattr__ method. We
have covered the fallback path, dynamic methods, lazy loading, proxies, and
__dir__ integration. For related topics, see
Python __getattribute__ method,
Python __dir__ method, and
Python getattr() function.
Author
List all Python tutorials.