In Python, setattr(obj, "name", value) does the same as obj.name = value, but the attribute name is a string. That lets you create or update attributes whose names come from data, such as the keys of a dictionary.
It creates the attribute if it does not exist yet and replaces it otherwise. It goes through the normal assignment machinery, so property setters and __setattr__ still run. Some objects refuse new attributes and raise AttributeError.
setattr() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Pass the object, the attribute name, and the value.
python
setattr(obj, "name", value)
Call
What it does
setattr(cfg, "debug", True)
Same as cfg.debug = True.
setattr(obj, key, value)
Name taken from a variable.
setattr(Class, "x", 1)
Sets a class attribute.
setattr(object(), "x", 1)
Raises AttributeError.
setattr() always returns None; it changes the object in place.
Library declarations
python
setattr(object, name, value, /)
Parameters
Parameter
Description
object
Required. The object to modify.
name
Required. The attribute name as a string.
value
Required. The new value.
Return Value
Return Value
Description
None
Nothing; the object is modified.
Python Examples
Example 1 — Create Attributes by Name
Add two attributes to an empty object and then use them normally.
Created on demand. Neither attribute existed; setattr() creates both.
Normal attributes. Afterwards cfg.level += 1 works like with any attribute.
Stored in __dict__.vars(cfg) lists the names that were added.
Returns None. The call is used for its effect, not its result.
Example 2 — Set Many Attributes from Keyword Arguments
Turn keyword arguments into attributes, then apply a dict of updates.
python
class Settings:
def __init__(self, **options):
for key, value in options.items():
setattr(self, key, value)
s = Settings(theme="dark", font_size=14)
print(s.theme, s.font_size)
updates = {"theme": "light", "font_size": 16}
for key, value in updates.items():
setattr(s, key, value)
print(s.theme, s.font_size)
Output
dark 14
light 16
How It Works
Flexible constructor. Every keyword argument becomes an attribute with the same name.
Loop over pairs. The dict's keys are attribute names and its values are the new values.
Overwrite existing. The second loop replaces theme and font_size.
Validate in real code. Checking keys against an allowed list prevents typos from creating stray attributes.
Example 3 — Objects That Reject New Attributes
Try setattr() on a slotted class, a read-only property, and a bare object().
python
class Point:
__slots__ = ("x", "y")
class Circle:
@property
def area(self):
return 3.14
p = Point()
setattr(p, "x", 1)
print(p.x)
for target, name in [(p, "z"), (Circle(), "area"), (object(), "tag")]:
try:
setattr(target, name, 0)
except AttributeError:
print("cannot set", name, "on", type(target).__name__)
Output
1
cannot set z on Point
cannot set area on Circle
cannot set tag on object
How It Works
Allowed slot.x is listed in __slots__, so it can be set.
Unknown slot.z is not listed and slotted objects have no __dict__.
Read-only property. A property without a setter rejects assignment.
Bare object.object() has no attribute storage at all.
Frequently Asked Questions
It sets an attribute by name: setattr(obj, "x", 5) is the same as obj.x = 5.
Loop over the items: for key, value in data.items(): setattr(obj, key, value).
The object may use __slots__, have a read-only property, or have no __dict__, like object().
Yes. It uses normal attribute assignment, so setters and __setattr__ run.