python / expert
Snippet
Descriptor-Based Model Field Property Access for Dynamic Type Casting
Custom Python descriptors intercept attribute access on model instances to perform runtime type casting while maintaining primitive underlying storage formats inside instance state dictionaries.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class TypedAttributeDescriptor:def __init__(self, field_name: str, target_type: type):self.field_name = field_nameself.target_type = target_typedef __get__(self, instance, owner=None):if instance is None:return selfraw_val = instance.__dict__.get(self.field_name)if raw_val is None:return Nonereturn self.target_type(raw_val)def __set__(self, instance, value):instance.__dict__[self.field_name] = str(value) if value is not None else None
django
Breakdown
1
def __get__(self, instance, owner=None):
Python descriptor getter invoked upon accessing the attribute on a class instance.
2
if instance is None: return self
Returns descriptor reference itself when accessed directly via the class object rather than instance.
3
return self.target_type(raw_val)
Dynamically coerces raw string dictionary values into target object types upon access.