In Python, the setattr() function is used to dynamically set an object's attribute value.

Function Syntax

setattr(object, name, value)

Parameters:

  • object: The object whose attribute is to be set.
  • name: The name of the attribute.
  • value: The value to set for the attribute.

If the object already has an attribute with the same name, its value will be overwritten.

The setattr() function can only be used to set attributes of objects or classes. It cannot be used to set attributes of modules or built-in types.

Examples of the setattr() Function

Basic usage:

class Person:
    pass

p = Person()
setattr(p, 'age', 30)
print(p.age)   # 30

Commonly used for dynamically setting attributes:

class Config:
    pass

cfg = Config()

attributes = {
    'host': 'localhost',
    'port': 8080,
    'timeout': 30
}

for key, value in attributes.items():
    setattr(cfg, key, value)

print(cfg.host)     # localhost
print(cfg.port)     # 8080
print(cfg.timeout)  # 30

Dynamically creating a class and setting attributes:

def create_dynamic_class(class_name, **kwargs):

    DynamicClass = type(class_name, (), {})

    instance = DynamicClass()

    for key, value in kwargs.items():
        setattr(instance, key, value)
    
    return instance

cfg = create_dynamic_class(
    'Config',
    host='localhost',
    port='8080',
    timeout=30
)

print(type(cfg))  # <class '__main__.Config'>
print(cfg.host)   # localhost
print(cfg.port)   # 8080
print(cfg.timeout) # 30