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...")
 
 
(One intermediate revision by the same user not shown)
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.
   
 
<nowiki>
 
<nowiki>
  +
# This code is licensed under the GPLv3 or later.
  +
# See https://www.gnu.org/licenses/gpl.html for the terms and conditions.
  +
 
import weakref
 
import weakref
   

Latest revision as of 02:46, 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.

# 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]