setattr()
setattr(object, name, value) Returns:
None · Updated March 13, 2026 · Built-in Functions built-in attributes objects
The setattr() function sets an attribute on an object using its name as a string. It provides runtime attribute assignment, which is useful when the attribute name is not known until the code executes.
Syntax
setattr(object, name, value)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
object | object | — | Any object that supports attribute assignment |
name | str | — | The attribute name as a string |
value | any | — | The value to assign to the attribute |
Examples
Basic usage
class Person:
pass
person = Person()
setattr(person, "name", "Alice")
setattr(person, "age", 30)
print(person.name)
# Alice
print(person.age)
# 30
Dynamic attribute assignment
class Config:
pass
config = Config()
settings = {"host": "localhost", "port": 8080, "debug": True}
for key, value in settings.items():
setattr(config, key, value)
print(config.host)
# localhost
print(config.debug)
# True
Setting attributes on existing objects
import math
setattr(math, "MY_CONSTANT", 42)
print(math.MY_CONSTANT)
# 42
Common Patterns
Building objects dynamically
def create_object(cls_name, **attrs):
cls = type(cls_name, (), {})
obj = cls()
for key, value in attrs.items():
setattr(obj, key, value)
return obj
user = create_object("User", name="Bob", email="bob@example.com")
print(user.name)
# Bob
Combining with getattr
class Robot:
def __init__(self):
self.x = 0
self.y = 0
robot = Robot()
setattr(robot, "direction", "north")
direction = getattr(robot, "direction", "unknown")
print(direction)
# north
Errors
- AttributeError: Raised when the object does not allow attribute assignment (e.g., frozen objects)
- TypeError: Raised when
nameis not a string
See Also
- built-in::getattr — retrieve an attribute by name
- built-in::hasattr — check if an attribute exists
- built-in::delattr — delete an attribute by name