Lazy Attributes for Python Objects
The `lazy` library (version 1.6) provides a Python descriptor that allows object attributes to be computed only when they are first accessed, and then caches the result for subsequent retrievals. It enables efficient resource usage by deferring potentially expensive computations until absolutely necessary. The project maintains an active, though not rapid, release cadence, with the latest update in 2023.
Warnings
- gotcha Lazy attributes are computed only once and then cached. If the underlying data or state that the lazy attribute depends on changes after its first access, the attribute will continue to return the stale cached value.
- gotcha Any side effects within the method decorated with `@lazy` (e.g., logging, modifying other object state) will occur only on the first access when the attribute is initially computed. Subsequent accesses will retrieve the cached value without re-executing the method.
- gotcha The library's `@lazy` decorator may not be inherently thread-safe. If multiple threads concurrently access a lazy attribute for the very first time, it could lead to the underlying computation running multiple times or result in a race condition for setting the cached value.
Install
-
pip install lazy
Imports
- lazy
from lazy import lazy
Quickstart
from lazy import lazy
class Foo(object):
@lazy
def bar(self):
print("computing bar")
return 42
f = Foo()
print(f.bar)
print(f.bar)