Python 3 reference · Built-in Functions

Python getattr() Function

Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.

Python 3 Since 3.0

Syntax

getattr(object, name)
getattr(object, name, default)

Parameters

ParameterDescription
object Any object.
name The attribute name as a string.
default optional Returned if the attribute doesn't exist.

Return value

The attribute's value, or default.

Examples

Read an attribute by nameTry it yourself
class User:
    name = "Ada"

u = User()
print(getattr(u, "name"))
print(getattr(u, "email", "no email"))

Output

Ada
no email
Call a method chosen at run timeTry it yourself
class Calculator:
    def add(self, a, b): return a + b
    def mul(self, a, b): return a * b

calc = Calculator()
for op in ["add", "mul"]:
    print(op, getattr(calc, op)(6, 7))

Output

add 13
mul 42

Good to know

getattr(obj, "x") is the same as obj.x; it is only useful when the name is in a variable. Without a default, a missing attribute raises AttributeError.

Version history

VersionChange
Python 3.0Added