python / expert
Snippet
Lazy Deserialization Field Descriptor for Django Models
Utilizes Python's descriptor protocol to lazily parse raw string attributes into structured JSON dictionaries upon property access.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import jsonfrom typing import Any, Typeclass LazyJSONDescriptor:def __init__(self, field_name: str):self.field_name = field_namedef __get__(self, instance: Any, owner: Type[Any]) -> Any:if instance is None:return selfraw_val = instance.__dict__.get(self.field_name)if isinstance(raw_val, str):parsed = json.loads(raw_val)instance.__dict__[self.field_name] = parsedreturn parsedreturn raw_valdef __set__(self, instance: Any, value: Any) -> None:instance.__dict__[self.field_name] = value
django
Breakdown
1
class LazyJSONDescriptor:
Defines a custom Python property descriptor for non-invasive model attribute management.
2
def __get__(self, instance: Any, owner: Type[Any]) -> Any:
Intercepts attribute read access on model instances.
3
raw_val = instance.__dict__.get(self.field_name)
Reads internal dictionary value directly without invoking descriptor recursion.
4
instance.__dict__[self.field_name] = parsed
Caches parsed data directly into instance dictionary for subsequent fast access.