Lazy Model
lazy-model is a Python library that provides a lazy interface for parsing objects into Pydantic models. It defers the parsing and validation of individual fields until they are explicitly accessed, saving the raw data within the object initially. This approach can significantly improve performance and reduce memory consumption, especially for large or complex data structures where not all fields are always needed immediately. The library is currently at version 0.4.0 and appears to have an active, though not rapid, release cadence, with its latest release in August 2025.
Warnings
- gotcha Fields parsed with `lazy_parse` are not fully validated by Pydantic until they are first accessed. This means initial model instantiation might succeed even if some lazily loaded fields contain invalid data, with validation errors only surfacing upon field access.
- gotcha The underlying mechanism of `lazy-model` interacts with Pydantic's internal object representation. While the library handles this, direct manual manipulation of `__dict__` for fields intended to be lazy can lead to unexpected behavior or bypass the lazy loading/validation mechanism.
Install
-
pip install lazy-model
Imports
- LazyModel
from lazy_model import LazyModel
Quickstart
from lazy_model import LazyModel
from pydantic import validator
class Sample(LazyModel):
i: int
s: str
@validator("s")
def s_upper(cls, v):
return v.upper()
# Create an instance with lazy parsing
obj = Sample.lazy_parse({"i": "10", "s": "test"})
# At this point, 'i' and 's' are stored in a raw format (NAO - Not An Object)
print(f"Initial object dict: {obj.__dict__}")
# Accessing 's' triggers its parsing and validation
print(f"Accessing s: {obj.s}") # Output: TEST
print(f"After 's' access: {obj.__dict__}")
# Accessing 'i' triggers its parsing and validation
print(f"Accessing i: {obj.i}, type: {type(obj.i)}") # Output: 10, <class 'int'>
print(f"After 'i' access: {obj.__dict__}") # Both fields are now parsed