Python Reference ยท Built-in Functions
Python getattr() function
Reference for Python getattr(): read an attribute by name, supply a default instead of AttributeError, and use it for dynamic dispatch and plugin lookups.
getattr(obj, "name") returns the value of the attribute called name, exactly like writing obj.name, except that the name is a string chosen at run time. With a third argument it returns that default value instead of raising AttributeError when the attribute is missing.
Use it when the attribute to read depends on data: dispatching to methods like handle_click, reading optional settings, or looking up a class in a module by name. When the name is fixed in your source, plain dot notation is clearer.
class Dog: sound = "woof" print(getattr(Dog(), "sound")) # woof
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
getattr(object, name) getattr(object, name, default)
| Name | Description |
|---|---|
object |
The object to read from: an instance, class, module and so on. |
name |
The attribute name, as a string. Names that are not valid identifiers work too. |
default |
Optional. Returned if the attribute does not exist. |
Return value: the attribute's value, or default.
Raises: AttributeError when the attribute is missing and no default was given; TypeError if name is not a string.
Usage notes
- Same lookup as the dot. Instance attributes, class attributes, inherited ones, properties and descriptors all work, and
__getattr__is consulted when normal lookup fails. - Only
AttributeErroris swallowed. If a property raises another exception,getattr()with a default still raises it. - Methods come back bound.
getattr(obj, "method")gives a bound method you can call later. - Default is evaluated eagerly, because it is an argument. Use a
try/exceptor a sentinel for expensive defaults. - Distinguish
Nonefrom missing. Use a uniqueobject()as the default ifNoneis a valid stored value. - Be careful with untrusted names. Letting users choose attribute names can expose internals. Validate against an allowlist.
- Pair functions:
setattr(),hasattr()anddelattr()complete the set;operator.attrgetter()is a fast callable for sorting and mapping, and supports dotted paths.