Lazy Model

0.4.0 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This example demonstrates how to define a `LazyModel` and use `lazy_parse` to defer field validation until access. It also shows that Pydantic validators still apply when a field is accessed for the first time.

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

view raw JSON →