Python Descriptors: How Attribute Access Really Works

This article explains the descriptor protocol behind properties, methods and cached properties, the precedence of data and non-data descriptors, and how to write reusable descriptors without their usual pitfalls.

A green tree python seen from above, its head resting between two of its own coils
Photo by Sebastian Spindler on Unsplash

The present article addresses descriptors, the protocol that decides what happens when an attribute is read, assigned or deleted. The expression obj.attr looks like a simple lookup in a dictionary, yet it is the point at which @property runs a method, a function becomes a bound method that receives self, and a slot defined with __slots__ finds its value. All of these behaviours rest on a single mechanism, which is the secret weapon that the following sections examine.

The Descriptor Protocol

The present section defines the protocol and builds a first descriptor with it. A descriptor is an object that defines at least one of three special methods, __get__(self, instance, owner), __set__(self, instance, value) and __delete__(self, instance), and that is stored as an attribute of a class. When an instance of that class accesses the attribute, Python calls the corresponding method of the descriptor instead of returning the descriptor itself. The following descriptor logs every read and every assignment.

class Logged:
    def __set_name__(self, owner, name):
        self.public_name = name
        self.private_name = "_" + name

    def __get__(self, instance, owner=None):
        if instance is None:  # Accessed on the class, not on an instance.
            return self
        value = getattr(instance, self.private_name)
        print(f"get {self.public_name} -> {value!r}")
        return value

    def __set__(self, instance, value):
        print(f"set {self.public_name} = {value!r}")
        setattr(instance, self.private_name, value)

class Account:
    balance = Logged()

    def __init__(self, balance):
        self.balance = balance

account = Account(100)        # Output: set balance = 100
account.balance += 50         # Output: get balance -> 100, then set balance = 150
print(vars(account))          # Output: {'_balance': 150}
print(type(Account.balance).__name__)  # Output: Logged

Three details of this example deserve attention. The method __set_name__, added by PEP 487 in Python 3.6 and already mentioned in the article devoted to metaclasses, tells the descriptor the name of the attribute to which it was assigned, so that the same class can serve several attributes without collisions. The value is stored on the instance under a private name, because the descriptor is a single object shared by every instance. Finally, __get__ returns the descriptor itself when instance is None, which is the case when the attribute is read on the class.

Functions Are Descriptors: How Methods Receive self

Every function defined in a class is a descriptor, and this fact answers a question that Python programmers rarely ask: how a method receives self without any explicit argument. A function has a __get__ method that, when it is called with an instance, returns a bound method that remembers that instance.

class Greeter:
    def hello(self):
        return f"hello from {type(self).__name__}"

greeter = Greeter()
function = Greeter.__dict__["hello"]

print(type(function).__name__)        # Output: function
bound = function.__get__(greeter, Greeter)
print(type(bound).__name__)           # Output: method
print(bound())                        # Output: hello from Greeter
print(hasattr(function, "__set__"))   # Output: False

The expression greeter.hello performs exactly this call to __get__ behind the scenes, and the bound method inserts greeter as the first argument when it is invoked. The last line shows that a function defines __get__ but not __set__, which places it in the category of non-data descriptors, a distinction that determines the order of attribute lookup.

Data and Non-Data Descriptors

A descriptor that defines __set__ or __delete__ is a data descriptor, and one that defines only __get__ is a non-data descriptor. Consequently, when Python resolves obj.attr, it applies the following order of precedence:

  1. A data descriptor found on the class.
  2. An entry of the instance dictionary, obj.__dict__.
  3. A non-data descriptor or an ordinary attribute found on the class.

The following example places a value with the same name in the instance dictionary and shows which source wins in each case.

class Data:
    def __get__(self, instance, owner=None):
        return "from the data descriptor"

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

class NonData:
    def __get__(self, instance, owner=None):
        return "from the non-data descriptor"

class Demo:
    data = Data()
    non_data = NonData()

demo = Demo()
demo.__dict__["data"] = "from the instance dictionary"
demo.__dict__["non_data"] = "from the instance dictionary"

print(demo.data)      # Output: from the data descriptor
print(demo.non_data)  # Output: from the instance dictionary

This order explains two everyday behaviours. A method can be shadowed by assigning an attribute with the same name to an instance, because functions are non-data descriptors; a property, on the other hand, cannot be bypassed in that way, because it is a data descriptor.

property Is a Descriptor

The built-in property is a data descriptor that delegates its three operations to the functions it receives. The decorator syntax only builds that object and assigns it to the class attribute, as the following class shows.

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("temperature below absolute zero")
        self._celsius = value

class ReadOnly:
    @property
    def version(self):
        return "1.0"

print(type(Temperature.__dict__["celsius"]).__name__)  # Output: property

try:
    Temperature(-300)
except ValueError as error:
    print(error)  # Output: temperature below absolute zero

try:
    ReadOnly().version = "2.0"
except AttributeError as error:
    print(error)  # Output: property 'version' of 'ReadOnly' object has no setter

Even the assignment inside __init__ passes through the setter, so the validation also protects the construction of the object. The second class demonstrates that a property without a setter is still a data descriptor: the assignment fails instead of creating an entry in the instance dictionary.

Reusable Validation

A property validates one attribute of one class, whereas a descriptor class can validate any number of attributes in any number of classes. Some online role-playing games offer an appropriate image for this difference: a piece of equipment has sockets, and the same kind of crystal grants the same effect to any piece that receives it. This means that the descriptor class plays the part of the crystal and each class attribute plays the part of a socket, as the following validator shows.

class PositiveNumber:
    def __set_name__(self, owner, name):
        self.private_name = "_" + name

    def __get__(self, instance, owner=None):
        if instance is None:
            return self
        return getattr(instance, self.private_name)

    def __set__(self, instance, value):
        if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
            raise ValueError(f"expected a positive number, got {value!r}")
        setattr(instance, self.private_name, value)

class Product:
    price = PositiveNumber()
    quantity = PositiveNumber()

    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity

apple = Product(price=1.5, quantity=100)
print(apple.price, apple.quantity)  # Output: 1.5 100

for price, quantity in ((-0.5, 50), (2.0, True)):
    try:
        Product(price, quantity)
    except ValueError as error:
        print(error)
# Output: expected a positive number, got -0.5
# Output: expected a positive number, got True

The explicit exclusion of bool is necessary because True is an instance of int and would otherwise pass as the number 1. The analogy, however, stops at this point: a crystal belongs to one piece of equipment, whereas a single descriptor object is shared by every instance of the class, which is why the value must be stored on each instance and never on the descriptor.

Lazy Attributes with cached_property

A non-data descriptor can compute a value on the first access and then step aside. The decorator functools.cached_property, available since Python 3.8, applies this idea: on the first read it calls the function and stores the result in the instance dictionary under the same name, and from then on the dictionary entry wins, according to the precedence described above.

from functools import cached_property

class Report:
    def __init__(self, rows):
        self.rows = rows

    @cached_property
    def total(self):
        print("computing total")
        return sum(self.rows)

report = Report([10, 20, 30])
print(report.total)            # Output: computing total, then 60
print(report.total)            # Output: 60
print("total" in vars(report)) # Output: True

The second access does not call the function at all, because the attribute is found in the instance dictionary before the descriptor is consulted. This mechanism requires an instance dictionary, so cached_property cannot be combined with classes whose __slots__ omit __dict__, the trade-off described in the article devoted to __slots__; each slot, incidentally, is implemented as a data descriptor of its own.

Pitfalls of Descriptors

This section identifies the errors that appear most often in hand-written descriptors. Four pitfalls are distinguished, which are the following:

  1. State on the descriptor. A value stored as an attribute of the descriptor is shared by every instance of the owner class.
  2. Access from the class. A __get__ that ignores the case instance is None fails, or returns nonsense, when the attribute is read on the class, for example by documentation tools.
  3. Placement on the instance. A descriptor only works as a class attribute; assigned to an instance, it is stored as an ordinary value and its methods are never called.
  4. Hidden cost. Every access runs a Python function, so a descriptor on an attribute read in a tight loop adds a measurable overhead compared with a plain attribute.

The first pitfall is reproduced in the following example.

class SharedValue:
    def __get__(self, instance, owner=None):
        return self.value

    def __set__(self, instance, value):
        self.value = value  # Stored on the descriptor: shared by all instances.

class Point:
    x = SharedValue()

first, second = Point(), Point()
first.x = 1
second.x = 2
print(first.x)  # Output: 2

The assignment to second.x overwrites the value of first.x, because both instances share the only SharedValue object that exists. Storing the value on the instance, under a name obtained through __set_name__, avoids this error, as the previous examples do.

When to Write a Descriptor

Consequently, a custom descriptor is justified when the same attribute logic must be reused, and the standard tools cover most other cases. The criteria are summarized in the following table.

Need Recommended tool
Compute or validate one attribute of one class property
Compute a value once per instance functools.cached_property
Reuse the same validation or conversion across attributes and classes A descriptor class with __set_name__
Declarative fields, as in ORMs and form libraries Descriptors, often combined with metaclasses or __init_subclass__
Plain data with no logic An ordinary attribute or a dataclass field

Conclusion

It is concluded that the descriptor protocol is the mechanism that gives meaning to attribute access in Python, and that properties, methods, slots and cached properties are all descriptors that differ only in which of the three methods they implement. The distinction between data and non-data descriptors explains why a property cannot be shadowed while a method can, and why a cached value replaces its own descriptor after the first access. This magic, however, carries a constant obligation: a descriptor is shared by every instance, so the state it manages must always live on the instance. The method resolution order, which decides in which class Python finds a descriptor when several classes in a hierarchy define the same name, is the natural continuation of this topic and is developed in a future article of this series.