Python:LazyProperty

From Paddon.org
Jump to navigation Jump to search

Lazy Property Decorator

When a property is both expensive to compute and constant, the LazyProperty decorator may be used to cache the result.

# This code is licensed under the GPLv3 or later.
# See https://www.gnu.org/licenses/gpl.html for the terms and conditions.
 
import weakref

class LazyProperty(property):
    """LazyProperty is a property that caches its value."""

    def __init__(self, fget = None, fset = None, fdel = None, doc = None):
        super().__init__(fget, fset, fdel, doc)
        self._cache = weakref.WeakKeyDictionary()

    def __get__(self, obj, objtype = None):
        if not obj in self._cache:
            self._cache[obj] = super().__get__(obj, objtype)
        return self._cache[obj]

    def __set__(self, obj, value):
        super().__set__(obj, value)
        if obj in self._cache:
            # clear cached value
            del self._cache[obj]

    def __delete__(self, obj):
        super().__delete__(obj)
        if obj in self._cache:
            # clear cached value
            del self._cache[obj]