python icon

Descriptors & Properties

Expert Answer & Key Takeaways

Mastering Descriptors & Properties is essential for high-fidelity technical performance and advanced exam competency in 2026.

Descriptors & Properties: The Mechanics of Attribute Access (2026)

Descriptors are the low-level mechanism behind @property, classmethod, and staticmethod. They are objects that define the behavior of attribute access (Get, Set, Delete) for other objects.

1. The Proof Code (Validation Descriptor)

class PositiveInteger: """A descriptor that enforces positive integer values.""" def __set_name__(self, owner, name): # Stores the name of the attribute on the owner class 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) or value < 0: raise ValueError(f"{self.name} must be a positive integer") instance.__dict__[self.name] = value class Product: price = PositiveInteger() stock = PositiveInteger() if __name__ == "__main__": p = Product() p.price = 100 # p.price = -10 # Raises ValueError print(f"Price: {p.price}") # Output: # Price: 100

2. Execution Breakdown

  1. The Descriptor Protocol: Any object that implements __get__, __set__, or __delete__ is a descriptor. It must be defined as a Class Attribute on the owner class.
  2. Data vs. Non-Data Descriptors:
    • Data Descriptors implement both __get__ and __set__. They always take precedence over the instance dictionary.
    • Non-Data Descriptors implement only __get__. They can be overridden by an entry in the instance's __dict__.
  3. Interception: When you write obj.x, Python checks if x is a descriptor in the class. If it is, it calls type(obj).x.__get__(obj, type(obj)) instead of looking in obj.__dict__.
  4. The Property Decorator: @property is simply a high-level wrapper around the descriptor protocol, creating a data descriptor for you automatically.

3. Detailed Theory

Descriptors are the 'secret sauce' that makes Python's attribute system so flexible.

The Lookup Chain

When you access obj.attr, Python searches in this order:
  1. Data Descriptor in the class (and its parents).
  2. Instance __dict__.
  3. Non-Data Descriptor in the class.
  4. Class __dict__.
  5. __getattr__ method (if it exists).

Why use Descriptors?

  • Validation: Enforce rules for multiple attributes across different classes (like our PositiveInteger example) without repeating @property boilerplate.
  • Lazy Loading: Calculate an attribute value only when it's first accessed and then cache it in the instance dictionary.
  • Bound Methods: Every function in Python is a descriptor. When you access obj.method, the function's __get__ method returns a 'bound method' object that pre-fills the self argument.
[!TIP] Senior Secret: Use __set_name__ (introduced in 3.6) to automatically capture the attribute name from the class definition. This eliminates the need to pass the name (e.g., "price") manually into the descriptor's constructor, making your code cleaner and less error-prone.

Top Interview Questions

?Interview Question

Q:What is the difference between a Data and Non-Data descriptor?
A:
A Data Descriptor implements __set__ and has higher precedence than the instance dictionary. A Non-Data Descriptor only implements __get__ and can be overridden by a variable in the instance dictionary.

?Interview Question

Q:Where must a descriptor be defined?
A:
A descriptor must be defined as a Class Attribute, not an instance attribute. It acts as a shared 'manager' for that attribute across all instances of the class.

?Interview Question

Q:How does @property relate to descriptors?
A:
@property is a built-in class that implements the descriptor protocol. It maps attribute access to the getter, setter, and deleter functions you define.

Course4All Engineering Team

Verified Expert

Data Science & Backend Engineers

The Python curriculum is designed by backend specialists and data engineers to cover everything from basic logic to advanced automation and API design.

Pattern: 2026 Ready
Updated: Weekly