Python setattr() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

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)
CallWhat 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

ParameterDescription
objectRequired. The object to modify.
nameRequired. The attribute name as a string.
valueRequired. The new value.

Return Value

Return ValueDescription
NoneNothing; the object is modified.

Python Examples

Example 1 — Create Attributes by Name

Add two attributes to an empty object and then use them normally.

python
class Config:
    pass


cfg = Config()
setattr(cfg, "debug", True)
setattr(cfg, "level", 3)
cfg.level += 1
print(cfg.debug, cfg.level)
print(sorted(vars(cfg)))

How It Works

  1. Created on demand. Neither attribute existed; setattr() creates both.
  2. Normal attributes. Afterwards cfg.level += 1 works like with any attribute.
  3. Stored in __dict__. vars(cfg) lists the names that were added.
  4. 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)

How It Works

  1. Flexible constructor. Every keyword argument becomes an attribute with the same name.
  2. Loop over pairs. The dict's keys are attribute names and its values are the new values.
  3. Overwrite existing. The second loop replaces theme and font_size.
  4. 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__)

How It Works

  1. Allowed slot. x is listed in __slots__, so it can be set.
  2. Unknown slot. z is not listed and slotted objects have no __dict__.
  3. Read-only property. A property without a setter rejects assignment.
  4. 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.
None. It changes the object in place.

Next: sentinel()

Create a unique marker value (new in Python 3.15).

sentinel() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful