Built-in Functions and Types

setattr()

Assign an attribute selected by a string at runtime. The operation follows the target type’s assignment rules: descriptors, __setattr__ and slot restrictions may intercept or reject it. It can update an existing attribute or create a new one when allowed. Name mangling is not automatic. Use validated names rather than blindly copying untrusted keys into sensitive objects.

Formal Syntax & Structure

python syntaxpython
setattr(object, name, value, /)

Parameters & Attributes

NameTypeDescription
objectobjectAssignment target.
namestrAttribute name.
valueobjectValue to assign.

Return Value

None

Mutates the target when permitted; does not return the assigned value.

Working Example

Example Snippetpython
class Settings:    pass
settings = Settings()setattr(settings, "theme", "dark")print(settings.theme)print(setattr(settings, "theme", "light"))print(settings.theme)
Python Reference