Course contentsShow
← Python
Lesson 641 of 1,06010. Advanced Language FeaturesFree lesson

Distinguishing Data and Non-Data Descriptors

You will categorize descriptors based on the presence of __set__ or __delete__ to understand their priority in the attribute lookup chain.

In this lesson, you will learn how the presence of specific dunder methods determines whether a descriptor acts as a "data" or "non-data" descriptor, and why this distinction fundamentally changes Python’s attribute lookup priority.

Data vs. Non-Data Descriptors

When you define a class that implements the descriptor protocol, Python categorizes it based on which methods you include.

  • Data Descriptors: These define __set__ or __delete__. Because they handle assignment or deletion, they are "privileged."
  • Non-Data Descriptors: These only define __get__. They are strictly for read-only access.

Why the distinction matters

The distinction is critical because of the attribute lookup chain. When you access an attribute on an instance (e.g., obj.x), Python follows a specific order of operations:

  1. Data Descriptors: If x is a data descriptor in the class, Python always calls its __get__ method, even if you have defined obj.x = value (which would trigger the __set__ method).
  2. Instance Dictionary: If no data descriptor is found, Python checks the instance's __dict__.
  3. Non-Data Descriptors: If the attribute isn't in the __dict__, Python then looks for a non-data descriptor in the class.

Consider this example:

class DataDescriptor:
    def __get__(self, obj, objtype): return "Data!"
    def __set__(self, obj, value): print("Setting value...")

class NonDataDescriptor:
    def __get__(self, obj, objtype): return "Non-Data!"

class MyClass:
    data = DataDescriptor()
    non_data = NonDataDescriptor()

obj = MyClass()
obj.__dict__['data'] = "hidden"
obj.__dict__['non_data'] = "hidden"

print(obj.data)      # Prints: Data! (Descriptor overrides __dict__)
print(obj.non_data)  # Prints: hidden (Instance __dict__ overrides non-data descriptor)

In the code above, the DataDescriptor is so powerful that it shadows the entry in the instance dictionary. Conversely, the NonDataDescriptor is "weaker"—it only intervenes if the instance dictionary doesn't contain the key. Understanding this hierarchy allows you to decide whether your descriptors should protect attribute access strictly or serve as convenient accessors that can be bypassed by instance-level overrides.

Key Takeaway: Data descriptors (implementing __set__ or __delete__) override instance dictionaries, while non-data descriptors (only implementing __get__) are overridden by instance dictionaries.