In this lesson, you will learn how to move beyond simple properties by using the Descriptor Protocol to centralize validation logic, ensuring your objects remain in a valid state regardless of how many attributes they have.
Moving Beyond Properties
While @property is excellent for basic validation, it becomes repetitive when you need to enforce the same rules (like range checking or type verification) across dozens of attributes or multiple classes. A descriptor is a class that defines __get__, __set__, or __delete__ methods. When you assign an instance of this descriptor to a class attribute, Python intercepts access to that attribute, allowing you to run custom logic every time it is read or modified.
Creating a Reusable Validator
Imagine you are building a data model for a game where many attributes must be positive integers. Instead of writing a setter for every single field, you can define a PositiveInteger descriptor:
class PositiveInteger:
def __init__(self, name):
self.name = 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 Player:
health = PositiveInteger("health")
mana = PositiveInteger("mana")
def __init__(self, health, mana):
self.health = health
self.mana = mana
How It Works
When you set player.health = 100, Python doesn't just store the value. It calls the __set__ method of the PositiveInteger instance assigned to health. This method checks your condition—if the value is invalid, it raises an error, effectively preventing the Player object from ever entering a corrupt state.
By offloading the "how to validate" logic into a dedicated class, you decouple the business rules from your main data model. This makes your code DRY (Don't Repeat Yourself) and creates a consistent interface for attribute management that can be reused across your entire project.
Key Takeaway: The Descriptor Protocol allows you to encapsulate validation logic into reusable classes, enforcing state integrity across your data models without duplicating boilerplate code.