In this lesson, you will learn how to build a robust validation layer that intercepts attribute assignments to ensure your object data always matches the expected types.
Preventing Bad Data with Descriptors
In Python, objects are often flexible, which can be a double-edged sword. If a developer assigns a string to an attribute that is supposed to be an integer, your program might fail much later, making debugging difficult. By using the __set__ method of a descriptor, we can perform a "gatekeeper" check every time a value is assigned.
The Validation Gatekeeper
To enforce a type constraint, your descriptor needs to check the value passed into __set__ against an expected type. If the type doesn't match, you raise a TypeError immediately.
class TypedProperty:
def __init__(self, expected_type):
self.expected_type = expected_type
self.name = None # We will set this in __set_name__
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError(f"Expected {self.expected_type.__name__}, "
f"got {type(value).__name__}")
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
return instance.__dict__.get(self.name)
class Product:
price = TypedProperty(int)
name = TypedProperty(str)
def __init__(self, name, price):
self.name = name
self.price = price
Why this is powerful
When you instantiate Product("Widget", "cheap"), the descriptor immediately raises a TypeError because "cheap" is a str and the price attribute requires an int.
Instead of allowing the invalid data to persist inside your object, the descriptor acts as an automated validation layer. This forces your objects to maintain integrity from the moment of instantiation, preventing silent errors from propagating through your system. Because this logic is contained within the descriptor, you don't have to write repetitive if checks inside every __init__ or setter method you create.
Key Takeaway: By implementing logic within the __set__ method of a descriptor, you create a reusable validation guard that prevents invalid data types from ever being stored in your instance attributes.