Lazy Object Proxy

1.12.0 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

This quickstart demonstrates how to create a lazy object proxy. The `expensive_function` is wrapped by `lazy_object_proxy.Proxy`. The actual execution of `expensive_function` is delayed until `obj` is accessed for the first time (e.g., when printed). Subsequent accesses use the cached result without re-executing the wrapped function. [4, 6]

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

view raw JSON →