Python:LazyProperty
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
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]