ZetCode

Python __setattr__ Method

Last modified November 18, 2026 Python 3.15

Python calls __setattr__ for every attribute assignment. A class can override it to log, validate, transform or reject assignments. The crucial rule is to avoid recursion: never use ordinary attribute assignment inside the hook. This article covers the basic pattern, validation, read-only and frozen objects, case-insensitive attributes, strict schemas with __slots__ and value transformation.

The basic pattern

The hook receives the attribute name and value. Printing a message and then delegating to super().__setattr__ logs the assignment while still storing the value correctly.

basic.py
class Person:
    def __setattr__(self, name, value):
        print("setting", name, "to", value)
        super().__setattr__(name, value)


p = Person()
p.name = "Alice"
p.age = 30
print(p.name, p.age)

Both assignments were intercepted and the delegation stored them. Without super(), the values would not be saved at all.

$ python basic.py
setting name to Alice
setting age to 30
Alice 30

Validating values

The hook can check a value before delegating. Here a temperature cannot be set below absolute zero, and the exception prevents any partial assignment.

validation.py
class Temperature:
    def __setattr__(self, name, value):
        if name == "celsius":
            if not isinstance(value, (int, float)):
                raise TypeError("temperature must be numeric")
            if value < -273.15:
                raise ValueError("below absolute zero")
        super().__setattr__(name, value)


t = Temperature()
t.celsius = 25
print(t.celsius)
for bad in (-300, "hot"):
    try:
        t.celsius = bad
    except (TypeError, ValueError) as e:
        print(type(e).__name__, e)
print("still", t.celsius)

The stored value was unchanged after both failed attempts. Validation before delegation is what makes the check effective.

$ python validation.py
25
ValueError below absolute zero
TypeError temperature must be numeric
still 25

Avoiding infinite recursion

Writing self.name = value inside __setattr__ calls the same hook again and recurses until Python raises RecursionError. Delegating to super() or writing to __dict__ directly avoids the loop.

no_recursion.py
class Safe:
    def __setattr__(self, name, value):
        self.__dict__[name] = value.upper() if isinstance(value, str) else value


s = Safe()
s.greeting = "hello"
s.count = 3
print(s.greeting, s.count)

Direct access to self.__dict__ bypasses the hook, so strings were upper-cased without a recursive call. The same result could be achieved with super().__setattr__(name, transformed).

$ python no_recursion.py
HELLO 3

Read-only attributes

A protected name can be blocked after the initial setup. Using super().__setattr__ in __init__ installs the value without going through the guard.

readonly.py
class Constants:
    def __init__(self):
        super().__setattr__("_values", {"PI": 3.14159})
        super().__setattr__("_frozen", False)

    def __setattr__(self, name, value):
        if self._frozen and name in self._values:
            raise AttributeError("cannot modify " + name)
        super().__setattr__(name, value)

    def freeze(self):
        self._frozen = True


const = Constants()
print(const._values["PI"])
const.freeze()
try:
    const.PI = 3.14
except AttributeError as e:
    print(type(e).__name__, e)
const.EXTRA = 1
print(const.EXTRA)

Freezing only affects the protected names; new attributes are still allowed. The guard consults a flag set in __init__ so the initial setup is not blocked.

$ python readonly.py
3.14159
AttributeError cannot modify PI
1

Case-insensitive attributes

The hook can normalize names before storing them. A companion __getattr__ applies the same normalization when reading, so different spellings address the same value.

case_insensitive.py
class CaseInsensitive:
    def __init__(self):
        super().__setattr__("data", {})

    def __setattr__(self, name, value):
        self.data[name.lower()] = value

    def __getattr__(self, name):
        return self.data.get(name.lower())


d = CaseInsensitive()
d.Color = "blue"
d.COLOR = "red"
print(d.color)

The last assignment won because both names were lower-cased. The constructor must install data with super(); the old version omitted this and recursed infinitely on the first assignment.

$ python case_insensitive.py
red

A strict schema with __slots__

Combining __slots__ with __setattr__ rejects any attribute that is not part of the declared schema.

strict.py
class StrictPerson:
    __slots__ = ("name", "age")

    def __setattr__(self, name, value):
        if name not in self.__slots__:
            raise AttributeError("cannot add attribute " + name)
        super().__setattr__(name, value)


p = StrictPerson()
p.name = "Bob"
p.age = 40
print(p.name, p.age)
try:
    p.email = "bob@example.com"
except AttributeError as e:
    print(type(e).__name__, e)

The two declared fields were accepted and the unknown one was rejected. __slots__ also removes the instance dictionary, saving memory.

$ python strict.py
Bob 40
AttributeError cannot add attribute email

Transforming values

A common use is converting values as they are assigned. Here every numeric value is coerced to float, while other values pass through.

transform.py
class NumericFields:
    def __setattr__(self, name, value):
        if isinstance(value, (int, float)) and not isinstance(value, bool):
            value = float(value)
        super().__setattr__(name, value)


class Measurement(NumericFields):
    pass


m = Measurement()
m.length = 5
m.label = "desk"
print(m.length, type(m.length).__name__)
print(m.label, type(m.label).__name__)

The number was converted once at assignment time; the string was left alone. Excluding bool avoids turning a boolean into 1.0, since bool is a subclass of int.

$ python transform.py
5.0 float
desk str

Best practices

A few rules keep __setattr__ safe:

Source

object.__setattr__ - Python documentation

Descriptor HowTo Guide - Python documentation

__slots__ - Python documentation

In this article we have implemented the __setattr__ method. We have covered interception, validation, recursion avoidance, read-only and frozen objects, case-insensitive names, strict schemas and transformation. For related topics, see Python __getattr__ method, Python __set__ method, and Python properties.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.