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.
pip install lazy-modelVerified import paths — ran on the pinned version, not inferred.
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.
Be aware that Pydantic's full validation for lazy fields occurs on first access. If strict upfront validation is required for all fields, consider using standard Pydantic model instantiation or explicitly accessing all fields after lazy parsing to trigger their validation.
Always interact with `LazyModel` instances and their fields through their public API and defined properties. Avoid directly manipulating `obj.__dict__` for lazily parsed fields unless you fully understand the implications and the library's internal workings.
Install the library using pip: `pip install lazy-model`
Ensure `lazy-model` is installed and the import path is correct. The primary class for lazy parsing is typically `LazyModel` from the top-level package: `from lazy_model import LazyModel`
Inspect the `ValidationError` details to identify which field failed validation and why. Correct the input data or adjust your Pydantic model's field types and validators to match the expected data format. Example: `try: model = MyLazyModel(data) except ValidationError as e: print(e.errors())`
Check your input data to ensure the field exists or verify your Pydantic model definition. If the field is optional, ensure it's handled gracefully (e.g., using `Optional[Type]`).
Ensure you are accessing dictionary elements using square brackets (`my_lazy_model.my_field['key']`) and not parentheses (`my_lazy_model.my_field('key')`). Verify that any Pydantic fields expecting callable types are provided with actual callable objects, or that data accessed lazily is of the expected type before operations.