all Python 3Built-in functionsterm
setattr
OOP
Sets an attribute of an object by name. Equivalent to obj.name = value, but lets you give the attribute name dynamically as a string.
Syntax
setattr(object, name, value)
Reach for setattr only when the attribute name is genuinely computed at runtime (from a config, a loop, user input); when you know the name up front, plain obj.x = value reads better and a typo in it gets flagged, while a typo inside a string does not. The name is not checked for being a valid identifier: setattr(obj, 'my attr', 1) happily lands in __dict__ and can then only be read back through getattr. Objects without a __dict__ — those with __slots__, or built-in types like int and str — raise AttributeError instead.
Examples
class A: pass
a=A()
setattr(a,'x',42)
print(a.x) # → 42
for name,val in [('p',1),('q',2)]:
setattr(a,name,val)
print(a.p, a.q) # → 1 2
setattr(a,'lst',[])
a.lst.append(1)
print(a.lst) # → [1]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy