🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreePython setattr: Assign Dynamic Attributes

Assigning an object’s attribute by a name held in a string is a task Python’s setattr() handles. The function assigns a value to the attribute named by that string.
This article shows how to assign values from a mapping and when to keep keyed data in a dictionary.
TL;DR: Python setattr()
Python setattr(object, name, value) assigns a value to an attribute whose name is held in a string.
- Use dot assignment when the attribute name is fixed in your code.
- Use setattr() when a string determines the attribute at runtime.
- Use a dictionary when the data should remain a collection of keys and values.
What Is setattr() in Python?
setattr() is a built-in function that assigns an attribute to an object using a string name. Its three arguments are the target object, the attribute name, and the value to assign.
For a fixed name, setattr(person, “age”, 30) has the same effect as person.age = 30. The function is useful when the name comes from a variable or a mapping, because dot notation would use the variable’s literal name instead.
Python’s function returns None after assignment. The name argument must be a string, but it need not be a valid identifier in all cases. Names with spaces, for example, can be assigned and read through setattr() and getattr(), though dot notation cannot express them.
How to Use setattr() Step by Step
Use a string variable for each attribute name, assign it to the target object, then retrieve it with getattr() or ordinary dot notation when its name is known.
Step 1: Assign names from a mapping
A mapping can hold configurable field names and values. This example applies two known settings to an ordinary instance, then reads one back by name.
class Settings:
pass
settings = Settings()
updates = {"theme": "dark", "retries": 3}
for name, value in updates.items():
setattr(settings, name, value)
print(settings.theme, settings.retries)
print(getattr(settings, "missing", "unset"))
class Limited:
__slots__ = ("name",)
limited = Limited()
try:
setattr(limited, "age", 4)
except AttributeError as error:
print(type(error).__name__ + ": " + str(error))
The output from python3 setattr_probe.py is:
dark 3
unset
AttributeError: 'Limited' object has no attribute 'age'

I ran python3 setattr_probe.py. The first line confirms both dynamic assignments, while getattr() returns its fallback for an absent name. The final line shows that __slots__ rejects an undeclared attribute.
Step 2: Choose attributes or dictionary keys
When incoming data is conceptually a set of fields on an object, setattr() makes those fields available through attribute access. When keys are arbitrary data, preserve the mapping and use indexing instead.
data = {"region": "west", "retry_count": 2}
record = {}
for key, value in data.items():
record[key] = value
print(record["region"], record["retry_count"])
This prints west 2. In the preceding probe, the object version prints the same values as attributes. I keep data in a dictionary when its keys are the data model, since that avoids confusing fields with an object’s methods or internal state.
setattr() Limits and Common Mistakes
setattr() follows the target object’s normal assignment rules, so it can fail or trigger class behavior rather than creating a plain instance field.
| Case | What happens | What to do |
|---|---|---|
| Name stored in a string | Attribute is assigned if allowed | Use setattr() |
| Object defines __slots__ without that name | AttributeError | Declare the slot or keep the value in a mapping |
| Property has a setter | Setter runs and may validate or reject the value | Check the property’s contract |
| Key is ordinary external data | May collide with object behavior | Use a dictionary or allow-list names first |
The captured slots failure is AttributeError: ‘Limited’ object has no attribute ‘age’. Limited declares only name in __slots__, so adding age is disallowed. Declare age in the slots or store it in a separate mapping.
A property setter can validate, transform, or reject an assigned value. A custom __setattr__() can also intercept assignments. The built-in function participates in these rules, while assigning directly to an instance’s __dict__ can skip them and does not work for every object.
Do not call __setattr__() directly for routine assignment. Implement a custom special method only when the class needs to control all assignments. Python’s data model explains these assignment hooks.
For attributes beginning with double underscores, remember that name mangling happens in source code at compilation. A string passed to setattr() is not mangled automatically.
For a fixed field, write ordinary assignment instead: person.age = 30 is clear for readers and tools to follow. For untrusted names, validate against allowed fields before setting anything.
Conclusion
Use setattr() when a string selects an object attribute at runtime, and use a mapping when the values are naturally keyed data. Python’s setattr() reference documents the built-in, and the data model reference explains assignment hooks. See AskPython’s Python object-oriented programming guide and magic methods guide for related concepts.
FAQ
These answers cover common questions about dynamic attribute assignment.
What does setattr() do in Python?
It assigns a value to an object’s attribute using a string for the attribute name.
Can setattr() add an attribute that does not exist?
Yes, if the target object permits that attribute. Objects with restrictive rules such as __slots__ may reject it.
What does setattr() return?
It returns None. Read the assigned value separately with getattr() or attribute access.
Should I use setattr() with a dictionary?
Use it when dictionary fields intentionally become object attributes. Keep values in a dictionary when arbitrary keys are data.


