Python Function Reference

getattr

Get the value of an attribute of an object by its name.

Python 3.13
getattr(object, name[, default])
  • [ ]optional part
object
The object to take the attribute from.
Any
name
The name of the attribute.
str
default
What to return if the attribute is missing, instead of raising AttributeError.
AnyOptional

Return value

The attribute value; raises AttributeError if it is missing and default is not given.

Examples

Calling a method by name

Python 3.13
print(getattr('hello', 'upper')())
HELLO

Default for a missing attribute

Python 3.13
print(getattr('hello', 'size', 0))
0

Details

getattr(x, 'size') is the same as x.size, but the attribute name can be stored in a variable.

See also