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.
setattr(point, "x", 10) # same as point.x = 10
Try it
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.
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
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 likeo.n = v. Frozen dataclasses raiseFrozenInstanceError(a subclass ofAttributeError). - 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 withgetattr(), not with dot syntax. - Built-in instances (
int,str,list) have no__dict__, sosetattr(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 withhasattr()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 ofsetattr()calls when setters matter. - Deleting is
delattr(); reading isgetattr().
Related
getattr(),hasattr(),delattr(),vars(),property()- Lessons: Classes, Properties