pyrex.internal_functions.lazy_property¶
-
pyrex.internal_functions.lazy_property(fn)¶ Decorator that makes a property lazily evaluated.
Acts like the standard python
propertydecorator, 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
LazyMutableClassClass for lazy properties dependent on attributes.
Notes
Using the
lazy_propertydecorator instead of the simple pythonpropertydecorator increases the time for property access (after the initial calculation) from ~0.5 microseconds to ~5 microseconds, solazy_propertyis 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
