From: Michael Tremer Date: Fri, 6 Oct 2017 15:49:01 +0000 (+0100) Subject: Add @lazy_property decorator X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=012035e093e37b34d3b8cf9d421cbaf99aa61f91;p=pbs.git Add @lazy_property decorator Signed-off-by: Michael Tremer --- diff --git a/Makefile.am b/Makefile.am index 64494a30..cd87e463 100644 --- a/Makefile.am +++ b/Makefile.am @@ -79,6 +79,7 @@ buildservice_PYTHON = \ src/buildservice/cache.py \ src/buildservice/constants.py \ src/buildservice/database.py \ + src/buildservice/decorators.py \ src/buildservice/distribution.py \ src/buildservice/git.py \ src/buildservice/__init__.py \ diff --git a/src/buildservice/decorators.py b/src/buildservice/decorators.py new file mode 100644 index 00000000..d6d948e7 --- /dev/null +++ b/src/buildservice/decorators.py @@ -0,0 +1,41 @@ +#!/usr/bin/python + +class lazy_property(property): + """ + The property is only computed once and then being + cached until the end of the lifetime of the object. + """ + def __init__(self, fget, fset=None, fdel=None, doc=None): + property.__init__(self, fget=fget, fset=fset, fdel=fdel, doc=doc) + + # Make a cache key + self._name = "_cache_%s" % self.fget.__name__ + + def __get__(self, instance, owner): + if instance is None: + return self + + if hasattr(instance, self._name): + result = getattr(instance, self._name) + else: + if not self.fget is None: + result = self.fget(instance) + + setattr(instance, self._name, result) + + return result + + def __set__(self, instance, value): + if instance is None: + raise AttributeError + + if self.fset is None: + setattr(instance, self._name, value) + else: + self.fset(instance, value) + + # Remove any cached attributes + try: + delattr(instance, self._name) + except AttributeError: + pass