In this lesson, you will learn how to use the descriptor protocol to create attributes that are calculated on-the-fly and protected from being overwritten.
The Power of Read-Only Descriptors
In Python, a descriptor is an object that defines how attribute access is handled. While we often use __get__ to fetch data, we can leverage the __set__ method to enforce immutability. If a class defines __set__ and explicitly raises an AttributeError, it effectively prevents any attempts to modify that attribute from the outside.
A "computed" property is one that doesn't exist as a static value in the __dict__ of an object, but is instead generated whenever it is accessed. By combining this logic with an error-raising setter, we create a robust, read-only interface.
Implementing the Read-Only Descriptor
Consider a scenario where you want a Circle object to provide an area that is calculated based on its radius, but you don't want anyone to manually "set" the area to a wrong value:
class ComputedArea:
def __get__(self, instance, owner):
if instance is None:
return self
return 3.14159 * (instance.radius ** 2)
def __set__(self, instance, value):
raise AttributeError("Cannot set read-only attribute 'area'")
class Circle:
area = ComputedArea()
def __init__(self, radius):
self.radius = radius
# Usage
c = Circle(10)
print(c.area) # Output: 314.159
c.area = 50 # Raises AttributeError: Cannot set read-only attribute 'area'
Why This Matters
By implementing __set__, the descriptor becomes a data descriptor. Even if a user tries to assign a value to c.area, the interpreter will call our __set__ method rather than adding a new entry to the instance's __dict__. This ensures that your calculated business logic remains the "source of truth" and cannot be tampered with by external code. This pattern provides a clean API while maintaining strict internal integrity.
Key Takeaway: By defining both __get__ and __set__ in a descriptor, you create a data descriptor that can compute values dynamically while enforcing immutability by explicitly raising an AttributeError within the setter.