setattr()
Sets an attribute on an object when the attribute name is in a string. It works like obj.name = value, but the name can come from data.
setattr(object, name, value)setattr(obj, "color", "red") does exactly what obj.color = "red" does. The name is a string, so it can come from a variable, a dictionary key or a settings file.
Its typical job is filling an object from data: loop over a dictionary and call setattr() for each key and value. If the attribute does not exist yet, it is created.
Built-in values such as numbers, strings and lists do not accept new attributes, so setattr() on them raises AttributeError. It works on objects of your own classes.
Parameters
| Parameter | What it is |
|---|---|
objectrequired | The object to change. |
namerequired | The attribute name, as a string. |
valuerequired | The new value. |
Return value
Nothing (None). The object is changed in place.
Examples
1The same as an assignment
class Profile:
pass
p = Profile()
p.name = "Hana"
setattr(p, "city", "Osaka")
print(p.name, p.city)Hana Osaka
2Fill an object from a dictionary
class Settings:
pass
data = {"theme": "dark", "font_size": 14, "language": "en"}
s = Settings()
for key, value in data.items():
setattr(s, key, value)
print(s.theme)
print(s.font_size + 2)dark 16
3Update an attribute chosen at run time
Read the current value with getattr(), change it, and write it back with setattr().
class Stock:
def __init__(self):
self.apples = 10
self.pears = 4
stock = Stock()
sold = [("apples", 3), ("pears", 1), ("apples", 2)]
for fruit, amount in sold:
setattr(stock, fruit, getattr(stock, fruit) - amount)
print(stock.apples, stock.pears)5 3
4Only accept known settings
class Config:
def __init__(self):
self.width = 800
self.height = 600
cfg = Config()
changes = {"width": 1024, "colour": "red"}
for key, value in changes.items():
if hasattr(cfg, key):
setattr(cfg, key, value)
else:
print("Unknown setting:", key)
print(cfg.width, cfg.height)Unknown setting: colour 1024 600
Checking with hasattr() first stops typos from creating new attributes by accident.
Common mistakes
Setting attributes on built-in values
Strings, numbers and lists have a fixed set of attributes, so you cannot add your own.
word = "hello"
try:
setattr(word, "language", "en")
except AttributeError:
print("AttributeError: cannot add attributes to a str")AttributeError: cannot add attributes to a str
Expecting setattr() to return the object
setattr() returns None. Writing obj = setattr(obj, "x", 1) replaces your object with None. Just call it on its own line.
Questions people ask
How do I delete an attribute by name?
Use delattr(obj, "name"), the same as del obj.name.
Can setattr() create a new attribute?
Yes, on ordinary objects of your own classes. If the name does not exist yet, it is added.
Should I use setattr() or a dictionary?
If the names are truly data (any key a user can type), a dictionary is usually clearer. Use setattr() when the names match real attributes of a class.