setattr
Set a new value for an attribute of an object, or create the attribute.
Python 3.13
setattr(object, name, value)- object
- The object whose attribute changes.Any
- name
- The name of the attribute.str
- value
- The new value of the attribute.Any
Return value
Nothing (None); the attribute is changed on the object itself.
Examples
New attribute on an object
Python 3.13
class User:
pass
user = User()
setattr(user, 'name', 'Anna')
print(user.name)Anna
Attributes from a settings dictionary
Python 3.13
class Config:
pass
config = Config()
for key, value in {'debug': True, 'level': 3}.items():
setattr(config, key, value)
print(config.debug, config.level)True 3
Details
setattr(x, 'name', 'Anna') is the same as x.name = 'Anna'. Strings, numbers and other built-in objects do not accept new attributes and raise AttributeError.
