Skip to content

Instantly share code, notes, and snippets.

@mrts
Created March 9, 2011 19:12
Show Gist options
  • Save mrts/862768 to your computer and use it in GitHub Desktop.
Save mrts/862768 to your computer and use it in GitHub Desktop.
Thread safe descriptor that combines memoizing (caching) and lazy loading
class LazyCachedDescriptor(object):
def __init__(self, fn, *args, **kwargs):
self.cache = None
self.fn = fn
self.args = args
self.kwargs = kwargs
def __get__(self, obj, objtype):
if self.cache is None:
result = [self.fn(*self.args, **self.kwargs)]
self.cache = result
return self.cache[0]
def reset(self):
self.cache = None
def func(*args, **kwargs):
print "func() was called with %s and %s" % (args, kwargs)
return "func() returned foo"
class consts(object):
FOO = LazyCachedDescriptor(func, 1, 'foo', b=3)
@classmethod
def reset(cls, attrib_name):
cls.__dict__[attrib_name].reset()
print consts.FOO
print consts.FOO
consts.reset('FOO')
print consts.FOO
print consts.FOO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment