ZetCode

Python __set__ Method

Last modified November 18, 2026 Python 3.15

A descriptor with a __set__ method is a data descriptor: Python calls it for every assignment to the managed attribute, even when the instance has an entry of the same name in its dictionary. This article shows __set_name__, validation, data versus non-data precedence, read-only attributes, lazy caching, a unit converter and a change-logging descriptor.

A basic data descriptor

The descriptor stores values in the instance dictionary under a private name. __set_name__ records the public attribute name when the class is created, so the descriptor does not need to hard-code it.

basic_set.py
class Logged:
    def __set_name__(self, owner, name):
        print("set_name:", owner.__name__, name)
        self.name = name

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return instance.__dict__.get(self.name)

    def __set__(self, instance, value):
        print("set:", self.name, value)
        instance.__dict__[self.name] = value


class Person:
    name = Logged()
    age = Logged()

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age!r})"


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

__set_name__ ran twice, once per managed attribute, before any instance existed. Each later assignment went through __set__, and reading used __get__.

$ python basic_set.py
set_name: Person name
set_name: Person age
set: name Alice
set: age 30
Person(name='Alice', age=30)

Validation on assignment

A descriptor can reject values before they are stored. This keeps the validation rule in one place, shared by every class that uses the descriptor.

validation.py
class Age:
    def __set_name__(self, owner, 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 not isinstance(value, int):
            raise TypeError("age must be an integer")
        if not 0 <= value <= 120:
            raise ValueError("age must be between 0 and 120")
        instance.__dict__[self.name] = value


class Person:
    age = Age()


p = Person()
p.age = 25
print(p.age)
for bad in (150, "25"):
    try:
        p.age = bad
    except (TypeError, ValueError) as e:
        print(type(e).__name__, e)

Both invalid assignments were rejected and the stored value stayed 25. Because the check lives in the descriptor, every class using Age gets the same rule.

$ python validation.py
25
ValueError age must be between 0 and 120
TypeError age must be an integer

Data versus non-data descriptors

A descriptor with __set__ outranks the instance dictionary. Without __set__, writing directly to the instance dictionary shadows the descriptor. This is the key difference between the two kinds.

precedence.py
class NonData:
    def __get__(self, instance, owner):
        return "computed"


class WithSet:
    def __get__(self, instance, owner):
        return "computed"

    def __set__(self, instance, value):
        instance.__dict__["with_set"] = value


class Example:
    non_data = NonData()
    with_set = WithSet()


e = Example()
print(e.non_data, e.with_set)
e.__dict__["non_data"] = "stored"
e.__dict__["with_set"] = "stored"
print(e.non_data, e.with_set)

The non-data value was shadowed by the dictionary entry, while the data descriptor still won. This precedence is why validation descriptors define __set__, even when it only raises an error.

$ python precedence.py
computed computed
stored computed

Read-only attributes

A data descriptor that raises in __set__ makes an attribute read-only. Because data descriptors take precedence, a direct write to the instance dictionary cannot bypass it.

readonly.py
class Constant:
    def __init__(self, value):
        self.value = value

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        raise AttributeError("attribute is read-only")


class Configuration:
    VERSION = Constant("1.0.0")


config = Configuration()
print(config.VERSION)
try:
    config.VERSION = "2.0.0"
except AttributeError as e:
    print(type(e).__name__, e)

The value was readable but any assignment raised immediately. This is a stronger guarantee than a property whose setter is simply omitted, because the descriptor controls the data descriptor path as well.

$ python readonly.py
1.0.0
AttributeError attribute is read-only

Lazy caching correctly

A non-data descriptor can cache a computed value in the instance dictionary: the first __get__ computes it, later reads find the cached entry because non-data descriptors have lower precedence. Adding __set__ here would break the cache.

lazy.py
class Lazy:
    def __init__(self, factory):
        self.factory = factory

    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, instance, owner):
        if instance is None:
            return self
        if self.name not in instance.__dict__:
            print("computing")
            instance.__dict__[self.name] = self.factory(instance)
        return instance.__dict__[self.name]


class Data:
    def __init__(self, values):
        self.values = values

    @Lazy
    def doubled(self):
        return [value * 2 for value in self.values]


data = Data([1, 2, 3])
print(data.doubled)
print(data.doubled)

The factory ran only once. The old version of this example defined __set__, which made it a data descriptor and caused the factory to run on every access — the cached dictionary entry was never used.

$ python lazy.py
computing
[2, 4, 6]
[2, 4, 6]

A property-like converter

A descriptor can keep two views of the same state in sync. Setting one value updates a second, derived attribute automatically.

converter.py
class Celsius:
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return instance._celsius

    def __set__(self, instance, value):
        instance._celsius = value
        instance._fahrenheit = value * 9 / 5 + 32


class Temperature:
    celsius = Celsius()

    def __init__(self, celsius=0):
        self.celsius = celsius

    @property
    def fahrenheit(self):
        return self._fahrenheit


temp = Temperature(100)
print(temp.fahrenheit)
temp.celsius = 0
print(temp.fahrenheit)

Assigning to celsius recomputed _fahrenheit transparently. The descriptor handles both the constructor call and later updates.

$ python converter.py
212.0
32.0

Logging changes

A descriptor can record how often an attribute changes. The counter lives on the instance and is created on first use, avoiding a second __set_name__ dependency for this simple case.

logging.py
class Tracked:
    def __set_name__(self, owner, name):
        self.name = name

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return instance.__dict__.get(self.name)

    def __set__(self, instance, value):
        key = "_" + self.name + "_updates"
        instance.__dict__[key] = instance.__dict__.get(key, 0) + 1
        instance.__dict__[self.name] = value


class Counter:
    value = Tracked()

    def __repr__(self):
        return f"Counter(value={self.value!r}, updates={self._value_updates})"


c = Counter()
c.value = 1
c.value = 2
print(c)

The counter incremented on each assignment and is visible alongside the value. This pattern is the basis for dirty flags and change tracking in object-relational mappers.

$ python logging.py
Counter(value=2, updates=2)

Best practices

A few rules keep __set__ well behaved:

Source

object.__set__ - Python documentation

Descriptor HowTo Guide - Python documentation

Descriptors - Python documentation

In this article we have implemented the __set__ method. We have covered descriptors, validation, precedence, read-only attributes, lazy caching, converters and change logging. For related topics, see Python __get__ method, Python __setattr__ 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.