getattr()
Dot access when the attribute name is a string — with an optional default that replaces try/except AttributeError.
Common call
value = getattr(obj, name, None)
Returns
the attribute, or default, or AttributeError
Replaces
try: obj.name except AttributeError: default
Watch out
without a default, AttributeError propagates — catch it or provide one
getattr(objectobject — Any object. getattr walks its class hierarchy to find the attribute.type: Any · required, name[, default])
→ Any
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | Any | yes | Any object. getattr walks its class hierarchy to find the attribute. |
| name | str | yes | The attribute name as a STRING. Not the identifier — a runtime value. |
| default | Any | no | The fallback value returned when the attribute is missing. Any type; None is common but a sentinel object is safer if None could be a real value. |
Return value
Any — The attribute value. If missing: returns default when supplied, raises AttributeError otherwise. The equivalent of `object.name` when `name` is a runtime string.
Common patterns
Optional attribute with a default
Replace try/except AttributeError with a one-line getattr.
timeout = getattr(config, "timeout", 30)
Dispatch by attribute name
Common in CLI parsers and plugin registries.
handler = getattr(handlers, command, default_handler) handler(*args)
Method call by runtime string
When the method name comes from data — config, user input, etc.
method = getattr(obj, name) result = method(*args, **kwargs)
Sentinel for the "None is a real value" case
When None could be legitimate, an object() sentinel disambiguates.
_missing = object() val = getattr(obj, name, _missing) if val is _missing: ... # truly absent
Examples
1. Method by name
getattr(str, "upper")
Returns
<method 'upper' of 'str' objects>2. Instance method
getattr("hi", "upper")()
Returns
"HI"3. With default
getattr(obj, "missing", "fallback")
Returns
"fallback"4. Without default
getattr({}, "missing")
Returns
AttributeError5. None as default
getattr(obj, "missing", None)
Returns
None6. Call after getattr
getattr(items, "sort")()
Returns
None # list.sort mutatesPitfalls
1. AttributeError without a default
The single most common getattr surprise. Without a third argument, a missing attribute raises AttributeError. In modern code, always provide a default unless you truly want the exception.
Uncaught raise
getattr(obj, "missing")
AttributeError: ...
Default it
getattr(obj, "missing", None)
None
2. A property that raises AttributeError looks "missing"
If a @property internally raises AttributeError, getattr returns the DEFAULT — the bug looks like the attribute is absent. Use try/except and log the error for properties with side effects.
Bug hidden
@property def x(self): return self.does_not_exist getattr(obj, "x", None)
None # bug looks like "missing"
Try/except with logging
try: val = obj.x except AttributeError as e: log.warning("no x: %s", e)
error visible
3. Class attributes AND instance attributes
getattr walks the MRO. A method defined on the class is returned via an instance getattr. For instance-only attributes, check obj.__dict__ or vars().
Assumed instance-only
class C: shared = 1 getattr(C(), "shared")
1 # from the class
Instance-only
vars(C()).get("shared")
None
4. Name is a STRING, not an identifier
A common typo — passing the attribute as if it were a variable. getattr wants the NAME as a string.
Not a string
getattr(obj, upper)
NameError: name 'upper' is not defined
Quote it
getattr(obj, "upper")
bound method
When to use
Use it
- Attribute access when the name is a runtime STRING
- Optional attributes with a fallback default
- Dispatch tables keyed by name — CLI, plugins, factories
- Method calls via reflection when the method name comes from data
Reach for something else
- You have a literal attribute name — use dot access directly
- You want to check existence only → hasattr
- You want the FULL exception on missing → skip the default and let AttributeError propagate
- Setting a value → setattr
Notes
Complexity
O(mro depth) — walks the class hierarchy
Return
The attribute value or default; may raise AttributeError
CPython impl
Python/bltinmodule.c :: builtin_getattr — calls PyObject_GetAttr
Memory
No allocation beyond the returned value
Thread-safe
Depends on whether attribute access is safe for the object
FAQ
For a literal attribute name, dot access (obj.name) is identical and clearer. getattr is for when the name is a runtime string — from config, from user input, from a computed value. Also useful for the third-arg default.
History
1.0
getattr() has been a builtin since Python 1.0.
3.2
Only AttributeError is caught internally when computing whether to use the default; other exceptions propagate.