Advertisement
Advanced Python, Descriptors & Properties

How would you implement a type-validating descriptor that enforces a specific type constraint, reusable across multiple attributes and classes?

Short answer

Build a generic descriptor class parameterized by the expected type (stored in __init__), and raise a TypeError inside __set__ if the assigned value doesn't match — combined with __set_name__ for automatic private-attribute naming, this gives you a fully reusable, DRY validation…

Save Python mock interview
Advertisement
AModel answer
Build a generic descriptor class parameterized by the expected type (stored in __init__), and raise a TypeError inside __set__ if the assigned value doesn't match — combined with __set_name__ for automatic private-attribute naming, this gives you a fully reusable, DRY validation mechanism applicable to any class.
class Typed:
    def __init__(self, expected_type):
        self.expected_type = expected_type
    def __set_name__(self, owner, name):
        self.name = f"_{name}"
    def __get__(self, instance, owner):
        return getattr(instance, self.name, None)
    def __set__(self, instance, value):
        if not isinstance(value, self.expected_type):
            raise TypeError(f"Expected {self.expected_type}, got {type(value)}")
        setattr(instance, self.name, value)

class User:
    name = Typed(str)
    age = Typed(int)
Real-world example
Building a reusable, DRY type-validation mechanism for class attributes without repeating validation logic in every __init__ or property setter.
Likely follow-ups
  • How does this hand-rolled Typed descriptor conceptually relate to what a library like pydantic does more comprehensively?
Related topics