PyREx

pyrex.internal_functions.lazy_property

pyrex.internal_functions.lazy_property(fn)

Decorator that makes a property lazily evaluated.

Acts like the standard python property decorator, but the first time the decorated property is accessed an attribute with the property’s name prefixed by ‘_lazy_’ will be created and the value of the property will be stored. Upon further access of the property, the stored value will be returned instead of recalculating it.

Parameters
fnfunction

Function returning class property which is to be decorated.

Returns
function

Lazy-evaluation property function.

See also

LazyMutableClass

Class for lazy properties dependent on attributes.

Notes

Using the lazy_property decorator instead of the simple python property decorator increases the time for property access (after the initial calculation) from ~0.5 microseconds to ~5 microseconds, so lazy_property is only recommended for use on properties with calculation times >5 microseconds which are likely to be accessed more than once.

Examples

>>> from time import sleep
>>> class A:
...     def __init__(self, value):
...         self.value = value
...     @lazy_property
...     def twice(self):
...         sleep(5)
...         return self.value*2
>>> a = A(1)
>>> "_lazy_twice" in a.__dict__
False
>>> a.twice
2
>>> "_lazy_twice" in a.__dict__
True
>>> a.twice
2

PyREx

A Python package for simulation of neutrinos and radio antennas in ice. Version 1.10.0

Navigation