diff --git a/rocketpy/tools.py b/rocketpy/tools.py new file mode 100644 index 000000000..f79a8e733 --- /dev/null +++ b/rocketpy/tools.py @@ -0,0 +1,21 @@ +_NOT_FOUND = object() + + +class cached_property: + def __init__(self, func): + self.func = func + self.attrname = None + self.__doc__ = func.__doc__ + + def __set_name__(self, owner, name): + self.attrname = name + + def __get__(self, instance, owner=None): + if instance is None: + return self + cache = instance.__dict__ + val = cache.get(self.attrname, _NOT_FOUND) + if val is _NOT_FOUND: + val = self.func(instance) + cache[self.attrname] = val + return val