1. Rhys !
  2. lyrcl-rhythmbox


lyrcl-rhythmbox / cachedProperty.py

from functools import update_wrapper

def cachedProperty(func, name=None):
    """cachedProperty(func, name=None) -> a descriptor
This decorator implements an object's property which is computed
the first time it is accessed, and which value is then stored in
the object's __dict__ for later use. If the attribute is deleted,
the value will be recomputed the next time it is accessed.
    class X(object):
      def foo(self):
        return computation()
    if name is None:
        name = func.__name__
    def _get(self):
            return self.__dict__[name]
        except KeyError:
            value = func(self)
            self.__dict__[name] = value
            return value
    update_wrapper(_get, func)
    def _del(self):
        self.__dict__.pop(name, None)
    return property(_get, None, _del)