Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Data Descriptors: How They Work and When to Use

Learn how Python data descriptors work, how they differ from non-data descriptors, and when to use them for validation, caching, and cleaner attribute access.

~5 min readPython
#descriptors#python#attribute access#magic methods
Diagram showing a Python data descriptor with __get__ and __set__ methods controlling attribute access between a class and an instance.

A Python data descriptor is an object that defines __get__ plus either __set__ or __delete__, giving it full control over how an attribute is read, written, or deleted on a class. The descriptor protocol is the mechanism behind property, classmethod, and staticmethod, but you can also build custom descriptors to enforce validation, cache computed values, or manage attribute lifecycle. Understanding the descriptor protocol is essential for writing clean, reusable attribute logic in Python.

The Descriptor Protocol

The descriptor protocol's core methods are __get__, __set__, and __delete__. An object that implements __get__ plus either __set__ or __delete__ is a data descriptor; one that implements only __get__ is a non-data descriptor. __set_name__ is an additional hook that tells a descriptor the attribute name it is assigned to. The __get__ method is called when the attribute is accessed, __set__ when it is assigned, and __delete__ when it is deleted.

python
class Descriptor: def __get__(self, instance, owner): return ... def __set__(self, instance, value): ... def __delete__(self, instance): ...

The instance argument is the object whose attribute is being accessed. The owner argument is the class through which the attribute is accessed, usually type(instance). When accessed on the class itself, instance is None. This distinction matters for implementing behavior that differs between instance and class access.

Data vs Non-Data Descriptors

Python's attribute lookup precedence determines whether a descriptor or an instance dictionary entry wins. For a data descriptor, __get__ takes precedence over the instance dictionary. For a non-data descriptor, the instance dictionary is checked first. This difference is why methods (non-data descriptors) can be overridden by assigning an instance attribute, while property (a data descriptor) cannot.

python
class NonData: def __get__(self, instance, owner): return "non-data" class Data: def __get__(self, instance, owner): return "data" def __set__(self, instance, value): pass class Example: nd = NonData() d = Data() ex = Example() ex.nd = "instance value" ex.d = "instance value" print(ex.nd) # "instance value" print(ex.d) # "data"

In this example, assigning to ex.nd shadows the non-data descriptor because the instance dictionary takes precedence. Assigning to ex.d still triggers the data descriptor's __set__, and reading it returns the descriptor's __get__ result.

Implementing a Simple Data Descriptor

A common use is enforcing a type or range on an attribute. Here is a descriptor that validates an integer is within a given range:

python
class IntegerRange: def __init__(self, min_value, max_value): self.min_value = min_value self.max_value = max_value 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): if not isinstance(value, int): raise TypeError(f"{self.name} must be an integer") if not self.min_value <= value <= self.max_value: raise ValueError(f"{self.name} must be between {self.min_value} and {self.max_value}") instance.__dict__[self.name] = value class Temperature: celsius = IntegerRange(-273, 1000) t = Temperature() t.celsius = 25 print(t.celsius) # 25 t.celsius = -300 # raises ValueError

The __set_name__ method is invoked when the containing class is created, and it receives the attribute name. Storing the value in instance.__dict__ avoids recursion because __set__ is called on every assignment; writing to instance.__dict__ directly bypasses the descriptor.

Common Use Cases for Descriptors

Descriptors are useful when you need to centralize behavior that would otherwise be duplicated across properties. Data descriptors are well suited for validation and logging because they intercept writes. Non-data descriptors are often used for caching and lazy loading because an instance assignment can shadow them and act as a reset. Common scenarios include:

  • Validation: Enforce types, ranges, or formats before assignment.
  • Caching: Compute a value once and store it; reset it when dependencies change.
  • Logging or auditing: Track every read or write to an attribute.
  • Lazy loading: Defer expensive computation until the attribute is accessed.

The following CachedProperty implements only __get__, so it is intentionally a non-data descriptor:

python
class CachedProperty: def __init__(self, func): self.func = func self.name = func.__name__ def __get__(self, instance, owner): if instance is None: return self if self.name not in instance.__dict__: instance.__dict__[self.name] = self.func(instance) return instance.__dict__[self.name] class Report: def __init__(self, data): self.data = data @CachedProperty def total(self): return sum(self.data)

This descriptor computes the total once and stores it in the instance dictionary. Subsequent accesses return the cached value without recomputation. Assigning to total on an instance stores a value in the instance dictionary and shadows the descriptor; deleting that instance attribute makes the descriptor compute the value again.

How Descriptors Interact with Class and Instance Attributes

When a descriptor is accessed on the class rather than an instance, __get__ receives instance=None. This is how property returns itself when accessed on the class. A well-behaved descriptor should handle this case explicitly, often by returning self or raising a descriptive error.

Descriptors must be stored as class attributes for the descriptor protocol to apply. A descriptor object placed in an instance dictionary is just a plain value, not a descriptor. In the earlier non-data example, assigning to ex.nd shadows the class-level descriptor; a data descriptor would intercept that assignment instead.

Performance and Overhead

Every attribute access through a descriptor adds a method call. In tight loops, this overhead can be measurable, but it is usually negligible compared to the cost of the logic inside __get__ or __set__. If performance is critical, consider whether a simple attribute with validation in a setter method would be sufficient. Descriptors shine when the same behavior is reused across many classes or attributes.

A more subtle performance concern is that storing values in instance.__dict__ via the descriptor can slow down attribute lookup slightly because the descriptor's __get__ must do a dictionary lookup. For most applications, this is acceptable. If you need maximum speed, you might combine descriptors with __slots__, but that adds complexity.

Pitfalls and Edge Cases

One common mistake is forgetting to implement __set__ when you want a data descriptor. If you only implement __get__, you get a non-data descriptor, and instance assignments will shadow it. Another pitfall is using a shared mutable state in the descriptor itself; each instance should store its own value in instance.__dict__, not in a descriptor attribute.

Another edge case is deletion. If you implement __delete__, you must handle the case where the attribute does not exist. Also, be careful when using descriptors with inheritance: subclasses inherit descriptors, but __set_name__ is not called again for the subclass. If you need behavior that depends on the subclass, inspect type(instance) in __get__ or __set__ at access time.

When to Choose a Descriptor Over Other Approaches

Python offers several ways to control attribute access: property, __getattr__, __setattr__, and descriptors. property is the simplest for a single attribute on one class. __getattr__ and __setattr__ intercept all attribute access on a class, but they are broad and can be hard to maintain. Descriptors are the right choice when you need to reuse the same logic across multiple attributes or classes, because they encapsulate the behavior in a single object.

For example, a descriptor that validates a value is between two limits can be reused on any number of attributes in different classes. A property would require duplicating the validation logic for each attribute. If you only need to handle one attribute, a property is often clearer.

A final consideration is maintainability. Descriptors introduce an indirection that can make code harder to follow if overused. Reserve them for cases where the abstraction pays off: repeated validation, caching, or cross-cutting attribute behavior. When in doubt, start with a property and refactor to a descriptor only when the duplication becomes evident.

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.