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.
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
| Parameter | What it is |
|---|---|
objectrequired | The object to read from. |
namerequired | The attribute name, as a string. |
defaultoptional | 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
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))Volta Volta 2021
2A default for missing attributes
class User:
def __init__(self, name):
self.name = name
u = User("Kenji")
print(getattr(u, "email", "no email given"))
u.email = "[email protected]"
print(getattr(u, "email", "no email given"))no email given [email protected]
3Print a report from a list of field names
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)}")number 1042 customer Ines total 58.4
4Call a method chosen by name
text = "Hello World"
for action in ["upper", "lower", "swapcase"]:
method = getattr(text, action)
print(action, "->", method())upper -> HELLO WORLD lower -> hello world swapcase -> hELLO wORLD
5Pick a function from a module
import math
for name in ["sqrt", "floor", "ceil"]:
func = getattr(math, name)
print(name, func(7.29))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.
class Box:
width = 10
b = Box()
try:
print(getattr(b, "height"))
except AttributeError:
print("AttributeError: Box has no height")
print(getattr(b, "height", 0))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).