CKTIS / Python
setattr()
Assigns an attribute whose name is supplied as a string.
Version: Python 3.14; repository image, production runtime not attested
Syntax
setattr(object, name, value, /)Assigns an attribute whose name is supplied as a string.
Assignment still follows the target type’s attribute rules. Slots can prohibit new attribute names.
The string is a dynamic attribute name, and assignment uses the type’s normal __setattr__ and descriptor rules. The width slot accepts 7; this instance has no dictionary or height slot, so that assignment raises AttributeError. Successful assignment returns None.
class Box:
__slots__ = ("width",)
b = Box()
assert setattr(b, "width", 7) is None and b.width == 7
Examples
class Box:
__slots__ = ("width",)
box = Box()
setattr(box, "width", 7)
print(box.width)
try:
setattr(box, "height", 8)
except AttributeError as error:
print(type(error).__name__)
Result
7 AttributeError
The string is a dynamic attribute name, and assignment uses the type’s normal `__setattr__` and descriptor rules. The width slot accepts 7; this instance has no dictionary or height slot, so that assignment raises AttributeError. Successful assignment returns None.