python / expert
Snippet
Descriptor Protocol for Type Safety
Descriptors are classes that define any of the methods __get__, __set__, or __delete__. They are used to implement custom logic for attribute access. In this snippet, __set_name__ automatically captures the attribute name, and __set__ enforces that the value assigned to 'age' is always an integer.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
class IntegerField:def __set_name__(self, owner, name):self.name = namedef __set__(self, instance, value):if not isinstance(value, int):raise ValueError(f'{self.name} must be an integer')instance.__dict__[self.name] = valueclass User:age = IntegerField()
Breakdown
1
def __set_name__(self, owner, name):
Called at class creation time to know the name assigned to the descriptor.
2
def __set__(self, instance, value):
Invoked whenever the managed attribute is assigned a value.
3
instance.__dict__[self.name] = value
Stores the value in the instance's dictionary to avoid infinite recursion.