baseimage-tutorial-framework/tfw/internals/lazy.py

28 lines
698 B
Python
Raw Normal View History

2018-10-09 09:25:11 +00:00
from functools import update_wrapper, wraps
class lazy_property:
"""
Decorator that replaces a function with the value
it calculates on the first call.
"""
def __init__(self, func):
self.func = func
update_wrapper(self, func)
def __get__(self, instance, owner):
if instance is None:
return self # avoids potential __new__ TypeError
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()