Built-in function

getattr()

Reads an attribute of an object when the attribute name is in a string, with an optional default value if the attribute is missing.

IntermediateEvery example below runs in your browser. Change the code and press Run.

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

getattr(obj, "color") does the same as obj.color. The difference is that the name is a string, so it can come from a variable, a list, a file or what a user typed.

Add a third argument and getattr() returns it when the attribute does not exist, instead of raising AttributeError. That makes optional settings easy: getattr(config, "timeout", 30).

Methods are attributes too. getattr(text, "upper") gives you the method itself; add () to call it. This lets you choose which method to run by name.

Parameters

ParameterWhat it is
object
required
The object to read from.
name
required
The attribute name, as a string.
default
optional
Returned when the attribute does not exist. Without it, a missing attribute raises AttributeError.

Return value

The value of the attribute, or default.

Examples

1Same as the dot, but with a string

Pythoneditable
class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

car = Car("Volta", 2021)
print(car.brand)
print(getattr(car, "brand"))
field = "year"
print(getattr(car, field))
Output
Volta
Volta
2021

2A default for missing attributes

Pythoneditable
class User:
    def __init__(self, name):
        self.name = name

u = User("Kenji")
print(getattr(u, "email", "no email given"))
u.email = "kenji@example.com"
print(getattr(u, "email", "no email given"))
Output
no email given
kenji@example.com

3Print a report from a list of field names

Pythoneditable
class Order:
    def __init__(self):
        self.number = 1042
        self.customer = "Ines"
        self.total = 58.4

order = Order()
for field in ["number", "customer", "total"]:
    print(f"{field:<10}{getattr(order, field)}")
Output
number    1042
customer  Ines
total     58.4

4Call a method chosen by name

Pythoneditable
text = "Hello World"
for action in ["upper", "lower", "swapcase"]:
    method = getattr(text, action)
    print(action, "->", method())
Output
upper -> HELLO WORLD
lower -> hello world
swapcase -> hELLO wORLD

5Pick a function from a module

Pythoneditable
import math

for name in ["sqrt", "floor", "ceil"]:
    func = getattr(math, name)
    print(name, func(7.29))
Output
sqrt 2.7
floor 7
ceil 8

Common mistakes

Not giving a default for an attribute that may be missing

Without a third argument, a missing attribute stops the program with AttributeError.

Pythoneditable
class Box:
    width = 10

b = Box()
try:
    print(getattr(b, "height"))
except AttributeError:
    print("AttributeError: Box has no height")
print(getattr(b, "height", 0))
Output
AttributeError: Box has no height
0

Using getattr() for dictionary keys

getattr(my_dict, "key") looks for an attribute, not a key, and fails. For dictionaries use my_dict.get("key", default).

Questions people ask

What is the difference between getattr() and the dot?

No difference in the result. Use the dot when you know the name while writing the code; use getattr() when the name is stored in a variable.

Is getattr() safe to use with user input?

It only reads attributes, but a user could still reach things you did not mean to expose. Check the name against a list of allowed names first.

How do I set an attribute by name?

Use setattr(): setattr(obj, "name", value).

Spotted a mistake on this page? Tell us