From 7fda9000c700ec5509fc3d5a3b61c89b74e51d9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Sch=C3=B6nberger?= Date: Tue, 6 Aug 2013 10:51:50 +0200 Subject: [PATCH] Add cached_property decorator --- skimage/_shared/utils.py | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/skimage/_shared/utils.py b/skimage/_shared/utils.py index ea631716..ae82bfbc 100644 --- a/skimage/_shared/utils.py +++ b/skimage/_shared/utils.py @@ -5,7 +5,7 @@ import sys from . import six -__all__ = ['deprecated', 'get_bound_method_class'] +__all__ = ['deprecated', 'cached_property', 'get_bound_method_class'] class deprecated(object): @@ -57,6 +57,38 @@ class deprecated(object): return wrapped +class cached_property(object): + """Decorator to use a function as a cached property. + + The function is only called the first time and each successive call returns + the cached result of the first call. + + class Foo(object): + + @cached_property + def foo(self): + return "Cached" + + Adapted from . + + """ + + def __init__(self, func, name=None, doc=None): + self.__name__ = name or func.__name__ + self.__module__ = func.__module__ + self.__doc__ = doc or func.__doc__ + self.func = func + + def __get__(self, obj, type=None): + if obj is None: + return self + value = obj.__dict__.get(self.__name__, _missing) + if value is _missing: + value = self.func(obj) + obj.__dict__[self.__name__] = value + return value + + def get_bound_method_class(m): """Return the class for a bound method.