Skip to content

Instantly share code, notes, and snippets.

@AndresMWeber
Created May 4, 2017 03:56
Show Gist options
  • Save AndresMWeber/4d578dec0fe80b6d35fb3bcbcc02024a to your computer and use it in GitHub Desktop.
Save AndresMWeber/4d578dec0fe80b6d35fb3bcbcc02024a to your computer and use it in GitHub Desktop.
Property caching decorator/property subclass
"""
Stolen from:
https://bytes.com/topic/python/answers/751180-how-memoize-cache-property-access
"""
class cached(property):
'Convert a method into a cached attribute'
def __init__(self, method):
private = '_' + method.__name__
def fget(s):
try:
return getattr(s, private)
except AttributeError:
value = method(s)
setattr(s, private, value)
return value
def fdel(s):
if private in s.__dict__:
del s.__dict__[private]
super(cached, self).__init__(fget, fdel=fdel)
@staticmethod
def reset(self):
cls = self.__class__
for name in dir(cls):
attr = getattr(cls, name)
if isinstance(attr, cached):
delattr(self, name)
if __name__ == '__main__': # a simple test
import itertools
counter = itertools.count()
class Test(object):
@cached
def foo(self):
return counter.next()
@cached
def bomb_moscow(self):
print 'fire missiles'
return counter.next() + 5
reset = cached.reset
a = Test()
print a.foo
print a.bomb_moscow
print a.bomb_moscow
print a.bomb_moscow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment