Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python setattr() function

Reference for Python setattr(): set an attribute by name at runtime, how it relates to dot syntax, properties, __slots__ and frozen objects, with examples.

The built-in setattr() function sets an attribute on an object when the attribute name is only known as a string at runtime. setattr(obj, "x", 5) does exactly what obj.x = 5 does, including calling a property setter or a custom __setattr__() if the class defines one.

You need it when names come from data: a configuration dictionary, a database column list, a form field name. For a fixed name, plain dot syntax is clearer and faster.

Python
setattr(point, "x", 10)   # same as point.x = 10

Try it

Python Setting attributes from data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Properties, slots and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
setattr(object, name, value)
Name Description
object The object that receives the attribute.
name A string, the attribute name.
value The value to store.

Return value: always None.

Raises: TypeError if name is not a string; AttributeError if the object refuses the attribute (built-in types, __slots__ without that name, read-only properties, frozen dataclasses).

Usage notes

  • Same as assignment. setattr(o, "n", v) triggers data descriptors, property setters and __setattr__(), just like o.n = v. Frozen dataclasses raise FrozenInstanceError (a subclass of AttributeError).
  • Any string is accepted as a name, even one that is not a valid identifier such as "not a valid name". You can only read it back with getattr(), not with dot syntax.
  • Built-in instances (int, str, list) have no __dict__, so setattr(5, "x", 1) fails.
  • It creates attributes. A typo in the name silently adds a new attribute instead of failing. When the set of fields is fixed, use __slots__ or check with hasattr() first.
  • Never use it with untrusted names on objects that hold sensitive state; a user-controlled name such as __class__ can change how the object behaves.
  • Classes work too. setattr(SomeClass, "limit", 10) adds a class attribute that all instances see.
  • Setting many at once. obj.__dict__.update(data) bypasses properties and descriptors, so prefer a loop of setattr() calls when setters matter.
  • Deleting is delattr(); reading is getattr().