python / expert
Snippet
Model Validation Descriptors for Type Enforcement in Django
Python descriptor protocol (`__get__`, `__set__`, `__set_name__`) integrated with model attribute instances allows encapsulating attribute-level type validation and sanitization logic prior to model database persistence.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
class StrictStringDescriptor:def __set_name__(self, owner, name):self.private_name = f'_{name}'def __get__(self, instance, owner):if instance is None:return selfreturn getattr(instance, self.private_name, '')def __set__(self, instance, value):if not isinstance(value, str):raise TypeError(f'Attribute must be a string, got {type(value).__name__}')setattr(instance, self.private_name, value.strip())
django
Breakdown
1
def __set_name__(self, owner, name):
Automatically captures field attribute names when assigned to a class body.
2
def __get__(self, instance, owner):
Custom descriptor access returning the internal instance variable or descriptor reference.
3
def __set__(self, instance, value):
Intercepts attribute assignment on instances to enforce strict runtime type constraints.