2018-10-09 09:25:11 +00:00
|
|
|
from functools import update_wrapper, wraps
|
2018-06-04 22:15:43 +00:00
|
|
|
|
2018-06-01 11:58:50 +00:00
|
|
|
|
2018-06-02 09:48:34 +00:00
|
|
|
class lazy_property:
|
2018-06-01 11:58:50 +00:00
|
|
|
"""
|
|
|
|
Decorator that replaces a function with the value
|
|
|
|
it calculates on the first call.
|
|
|
|
"""
|
|
|
|
def __init__(self, func):
|
|
|
|
self.func = func
|
2018-06-04 22:15:43 +00:00
|
|
|
update_wrapper(self, func)
|
2018-06-01 11:58:50 +00:00
|
|
|
|
|
|
|
def __get__(self, instance, owner):
|
|
|
|
if instance is None:
|
2018-06-02 09:25:48 +00:00
|
|
|
return self # avoids potential __new__ TypeError
|
2018-06-01 11:58:50 +00:00
|
|
|
value = self.func(instance)
|
|
|
|
setattr(instance, self.func.__name__, value)
|
|
|
|
return value
|
2018-10-09 09:25:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
def lazy_factory(fun):
|
|
|
|
class wrapper:
|
|
|
|
@wraps(fun)
|
|
|
|
@lazy_property
|
|
|
|
def instance(self): # pylint: disable=no-self-use
|
|
|
|
return fun()
|
|
|
|
return wrapper()
|