descriptor

In Python, a descriptor is an object attribute with binding behavior, meaning that its behavior is triggered when you access, set, or delete an attribute. Descriptors are a powerful feature that allows you to customize the way attributes are accessed or modified in your classes.

To create a descriptor, you implement the descriptor protocol methods: .__get__(), .__set__(), and .__delete__(). With these methods, you can control the attribute’s behavior when you access, modify, or delete it.

Descriptors let you manage the attributes of classes in a more controlled manner. Common use cases of descriptors include enforcing type checking, data validation, and implementing lazy attributes.

Example

Here’s a simple example to illustrate how a descriptor works:

Python
class Coordinate:
    def __set_name__(self, owner, name):
        self._name = name

    def __get__(self, instance, owner):
        return instance.__dict__[self._name]

    def __set__(self, instance, value):
        try:
            instance.__dict__[self._name] = float(value)
            print("Validated!")
        except ValueError:
            raise ValueError(f'"{self._name}" must be a number') from None

class Point:
    x = Coordinate()
    y = Coordinate()

    def __init__(self, x, y):
        self.x = x
        self.y = y

In this example, you define the Coordinate descriptor to validate and convert coordinate values to floats in the Point class. The Point class uses two Coordinate instances (.x and .y) to enforce numeric values for its .x and .y coordinates. It raises an error if you pass invalid values.

Tutorial

Python Descriptors: An Introduction

In this step-by-step tutorial, you'll learn what Python descriptors are and how they're used in Python's internals. You'll learn about the descriptor protocol and how the lookup chain works when you access an attribute. You'll also see a few practical examples where Python descriptors can come in handy.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 11, 2025 • Reviewed by Leodanis Pozo Ramos