setattr()
Dot assignment when the attribute name is a string — useful for dynamic dispatch and configuration.
Demo
The demo picks a target — a user class or a built-in type — and tries to set an attribute. USER CLASSES accept setattr and store the value in the instance __dict__. BUILT-IN TYPES (str, int, list, ...) reject setattr with TypeError because they are immutable. This is the same distinction you would see writing `str.x = 1` in real Python.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | Any | yes | The object to modify. Instances of user classes accept setattr; built-in types like int, str, list reject it. |
| name | str | yes | The attribute name as a STRING. Not the identifier — a runtime value. |
| value | Any | yes | The value to assign. Any type. Overwrites any existing attribute with the same name. |
Return value
None — Returns None. Sets the attribute `name` on `object` to `value` — equivalent to `object.name = value` when the name is known at runtime. Raises TypeError when the target is an immutable built-in type; raises AttributeError when the object cannot accept the attribute (e.g. __slots__ classes).
Common patterns
for key, value in config.items(): setattr(obj, key, value)
def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v)
def new_method(self): return 42 setattr(MyClass, "answer", new_method)
obj.name = "Alice" # clearer setattr(obj, "name", "Alice") # only if "name" is a variable
Examples
Pitfalls
setattr(str, "foo", 1)
class MyStr(str): pass setattr(MyStr, "foo", 1)
class P: __slots__ = ("x",) setattr(P(), "y", 1)
class P: __slots__ = ("x", "y") setattr(P(), "y", 1)
setattr(obj, 42, "x")
setattr(obj, "42", "x")
setattr(obj, name, new) # even if obj.name already exists
if not hasattr(obj, name): setattr(obj, name, new)
When to use
- Dynamic attribute assignment with a runtime name
- Configuring an object from a dict or kwargs
- Method injection (monkey-patching) — rare in modern code but occasionally useful
- Any place `obj.name = value` is needed but `name` is a variable
- You have a literal attribute name → use dot access
- The target is a built-in type → cannot be modified
- You want deletion → delattr
- You want to check first → hasattr + setattr, or just try/except
Notes
FAQ
Because built-in types (int, str, list, ...) are implemented in C and their layouts are fixed — no Python-level __dict__ exists. Attempting to add an attribute raises TypeError. Subclass the type if you need to attach attributes.