libb.lazy_property

lazy_property(fn)[source]

Decorator that makes a property lazy-evaluated.

Computes the property value only once on first access, then caches the result for subsequent accesses. Useful for expensive computations.

Parameters:

fn (Callable[[Any], TypeVar(R)]) – The property method to make lazy.

Return type:

property

Returns:

A lazy property descriptor.

Basic Lazy Evaluation:

>>> import time
>>> class Sloth:
...     def _slow_cool(self, n):
...         time.sleep(n)
...         return n**2
...     @lazy_property
...     def slow(self):
...         return True
...     @lazy_property
...     def cool(self):
...         return self._slow_cool(3)

Instantiation is Fast:

>>> x = time.time()
>>> s = Sloth()
>>> time.time()-x < 1
True
>>> time.time()-x < 1
True

First Access Triggers Computation:

>>> hasattr(s, '_lazy_slow')
False
>>> s.slow
True
>>> hasattr(s, '_lazy_slow')
True

Expensive Computation Happens Once:

>>> s.cool
9
>>> 3 < time.time()-x < 6
True
>>> s.cool
9
>>> 3 < time.time()-x < 6
True