Lazy Object Proxy
lazy-object-proxy is a Python library that provides a fast and thorough lazy object proxy implementation. It defers the initialization of an object until its first access, which can be highly beneficial for performance optimization and handling circular dependencies. The library is currently at version 1.12.0 and maintains an active development cycle with regular updates. [5, 10]
Warnings
- breaking Support for older Python versions has been progressively dropped. Version 1.12.0 requires Python >=3.9. Previous versions (e.g., 1.11.0, 1.10.0, 1.8.0, 1.7.1) dropped support for Python 3.8, 3.7, 3.6, and 2.7 respectively. [2, 6, 8]
- gotcha When `lazy-object-proxy`'s C extension fails to compile (e.g., due to missing build tools or specific environments like PyPy/GraalPy), it gracefully falls back to a pure Python implementation. While functional, this can result in a performance overhead. [11]
- gotcha The `__resolved__` property was added in version 1.6.0. Before this, there was no direct public API to check if the factory function had been called without triggering its execution. [2, 8]
- gotcha While `lazy-object-proxy` aims for transparency, deep introspection or specific type comparisons (especially direct `type()` checks) on the proxy object might not always yield the underlying object's type until it's resolved. `isinstance()` typically works as expected due to how proxies handle `__class__` attribute. [3]
Install
-
pip install lazy-object-proxy
Imports
- Proxy
from lazy_object_proxy import Proxy
Quickstart
import lazy_object_proxy
import time
def expensive_function():
"""Simulates an expensive operation."""
print('Starting expensive calculation...')
time.sleep(2) # Simulate work
print('Finished expensive calculation.')
return 'Expensive Result'
# The expensive_function is not called yet
obj = lazy_object_proxy.Proxy(expensive_function)
print('Proxy object created, but function not called yet.')
# The function is called only when the object is actually used
print(f'First access: {obj}') # This will trigger expensive_function
print(f'Second access: {obj}') # This will use the cached result