Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Using Python setattr for Dynamic Attribute Assignment

Learn how Python's setattr works, when to use it for dynamic attribute assignment, and common pitfalls to avoid.

~5 min readPython
#setattr#dynamic attributes#python builtins#object introspection
Illustration of Python setattr assigning a dynamic attribute to an object

Python's built-in setattr function assigns a value to an attribute on an object when the attribute name is not known until runtime. Its syntax is setattr(obj, name, value). The function treats name as a string and performs the equivalent of obj.name = value when name is a valid identifier. This becomes essential when you need to construct attribute names dynamically, such as when parsing configuration files, mapping database columns to object fields, or building flexible APIs.

How setattr Works

setattr is a built-in function that operates on any object that supports attribute assignment. It takes three arguments: the target object, the attribute name as a string, and the value to assign. Internally, it calls the object's __setattr__ method, which is the same method invoked by the dot-assignment syntax. This means that any behavior you get from obj.attr = value—including property setters, descriptors, and validation logic—also applies when you use setattr.

python
class Product: pass p = Product() setattr(p, 'name', 'Laptop') setattr(p, 'price', 999.99) print(p.name) # Laptop print(p.price) # 999.99

The function returns None and raises AttributeError if the object does not allow attribute assignment (for example, a tuple or a string). It also raises TypeError if the name is not a string. The name must be a valid Python identifier for the attribute to be accessible via dot notation; otherwise, you can only access it through getattr or vars().

When to Use setattr Over Direct Assignment

Direct assignment (obj.attr = value) is clearer and faster when the attribute name is static. Use setattr when the attribute name is computed or comes from an external source. Common scenarios include:

  • Mapping data from a dictionary to object fields without hardcoding each key.
  • Implementing a generic from_dict class method.
  • Building objects from configuration files where keys vary.
  • Creating attributes inside a loop when the names follow a pattern.
python
class User: def __init__(self, data): for key, value in data.items(): setattr(self, key, value) user_data = {'username': 'alice', 'email': 'alice@example.com', 'role': 'admin'} u = User(user_data) print(u.username) # alice

In this example, setattr avoids writing a separate assignment for each possible field. The same pattern works with database rows or JSON payloads, making the code adaptable to schema changes without modifying the class.

Setting Attributes on Instances and Classes

setattr works on both instances and classes. When you call setattr(MyClass, 'attr', value), you are setting a class attribute, which is shared by all instances unless an instance overrides it. This is useful for defining constants or default values dynamically.

python
class Config: pass setattr(Config, 'timeout', 30) setattr(Config, 'retries', 3) print(Config.timeout) # 30

You can also set attributes on a class after it has been defined, which is common in plugin systems or when loading modules dynamically. However, be cautious: setting attributes on classes that already have instances will affect those instances only if they do not have their own attribute with the same name.

Common Pitfalls and Edge Cases

One frequent mistake is using setattr with a name that is not a valid identifier, such as 'first name' or 'class'. While setattr will accept these strings, you cannot access them with dot notation. You must use getattr or vars() to retrieve them, which often defeats the purpose.

python
from types import SimpleNamespace obj = SimpleNamespace() setattr(obj, 'first name', 'Alice') print(getattr(obj, 'first name')) # Alice # print(obj.first name) # SyntaxError

Another pitfall is attempting to set attributes on objects that do not support them, such as built-in types or instances with __slots__ that do not include the attribute. For example, setattr(1, 'x', 5) raises AttributeError. Similarly, if a class defines __slots__ without the attribute name, setattr will fail unless the slot is listed.

python
class Slotted: __slots__ = ['a'] s = Slotted() setattr(s, 'b', 10) # AttributeError: 'Slotted' object has no attribute 'b'

Also, be aware that setattr invokes any property setter or descriptor defined for that attribute. If a property has a setter that validates input, setattr will trigger that validation. This is usually desirable, but it can surprise developers who expect setattr to bypass such logic.

Security and Validation Concerns

Using setattr with untrusted input can be risky. If an attacker controls the attribute name, they might overwrite critical methods or internal attributes, leading to broken object behavior or security vulnerabilities. For example, setting __class__ or __dict__ on an object can change how the object behaves in unexpected ways.

python
class BankAccount: def __init__(self, balance): self.balance = balance def withdraw(self, amount): if amount <= self.balance: self.balance -= amount else: raise ValueError('Insufficient funds') account = BankAccount(100) setattr(account, 'balance', 9999) # Directly sets balance, bypassing any checks

If you must use setattr with external input, validate the attribute names against an allowlist. Avoid allowing names that start with an underscore or that match known internal attributes. Also consider using a dedicated data class or a mapping instead of dynamically assigning attributes when the schema is predictable.

Performance and Runtime Behavior

setattr incurs a small overhead compared to direct assignment because it involves a function call and a string-based attribute lookup. In tight loops where performance is critical, direct assignment is preferable. However, for most application code, the difference is negligible. The larger cost comes from any custom __setattr__ logic, which runs regardless of the assignment method.

python
import timeit class A: pass a = A() def direct(): a.x = 1 def via_setattr(): setattr(a, 'x', 1) print(timeit.timeit(direct, number=1_000_000)) print(timeit.timeit(via_setattr, number=1_000_000))

The measured times will vary, but setattr is typically slower because of the extra function call and string lookup. If you are building an object from a large dictionary, the overhead is usually acceptable, but if you are setting thousands of attributes per second, consider a more targeted approach like using vars(obj).update(data) when the object is a simple instance without custom __setattr__.

Alternatives to setattr

For simple cases, you can use vars(obj).update(data) to set multiple attributes at once, provided the object has a __dict__ and no property restrictions. This is often faster and more concise.

python
class User: pass u = User() vars(u).update({'username': 'bob', 'email': 'bob@example.com'})

However, this bypasses any __setattr__ logic and does not work with __slots__. Another alternative is to use SimpleNamespace from the types module, which is designed for attribute-style access and accepts keyword arguments.

python
from types import SimpleNamespace ns = SimpleNamespace(username='alice', email='alice@example.com') print(ns.username)

SimpleNamespace is a lightweight option when you do not need a custom class. For data that is naturally a mapping, consider using a dictionary or a dataclass instead of dynamic attributes.

Advanced Usage: Descriptors and Metaclasses

setattr becomes more powerful when combined with descriptors or metaclasses. For instance, a descriptor that validates values can be installed dynamically using setattr on a class. This allows you to add behavior to classes at runtime.

python
class PositiveNumber: def __init__(self, name): self.name = name def __get__(self, instance, owner): if instance is None: return self return instance.__dict__[self.name] def __set__(self, instance, value): if value < 0: raise ValueError('Must be non-negative') instance.__dict__[self.name] = value class Order: pass setattr(Order, 'quantity', PositiveNumber('quantity')) order = Order() order.quantity = 5 print(order.quantity) # 5 # order.quantity = -1 # ValueError

Because setattr does not call __set_name__ when a descriptor is attached to an existing class, this version gives the descriptor its attribute name explicitly.

In metaclasses, the same dynamic-assignment techniques are common when processing the class namespace during class creation. For example, a metaclass can automatically convert attribute names to uppercase or wrap methods with decorators.

python
class UpperAttrMeta(type): def __new__(cls, name, bases, dct): upper_dct = {} for key, value in dct.items(): if not key.startswith('__'): upper_dct[key.upper()] = value else: upper_dct[key] = value return super().__new__(cls, name, bases, upper_dct) class MyClass(metaclass=UpperAttrMeta): foo = 1 print(MyClass.FOO) # 1

These advanced uses demonstrate that setattr is not just a convenience for dynamic assignment but a foundational tool for metaprogramming. When used deliberately, it enables flexible and maintainable code, but it requires careful attention to the object's contract and the data being assigned.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.