Difference between revisions of "Python:LazyProperty"

From Paddon.org
Jump to navigation Jump to search
(Created page with "= Python Lazy Property Decorator = When a property is both expensive to compute and constant, the LazyProperty decorator may be used to cache the result. <nowiki> import we...")
 
Line 1: Line 1:
= Python Lazy Property Decorator =
+
= Lazy Property Decorator =
   
 
When a property is both expensive to compute and constant, the LazyProperty decorator may be used to cache the result.
 
When a property is both expensive to compute and constant, the LazyProperty decorator may be used to cache the result.

Revision as of 00:27, 11 October 2018

Lazy Property Decorator

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

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]