2014-05-08 16:59:35 +00:00
|
|
|
def cached(func):
|
|
|
|
""" caches func return value """
|
|
|
|
def cached_func(self, *args, **kwargs):
|
2015-03-10 11:46:48 +00:00
|
|
|
# id(self) prevents sharing within subclasses
|
|
|
|
attr = '_cached_%s_%i' % (func.__name__, id(self))
|
2014-07-21 12:20:04 +00:00
|
|
|
key = (args, tuple(kwargs.items()))
|
|
|
|
try:
|
|
|
|
return getattr(self, attr)[key]
|
|
|
|
except KeyError:
|
|
|
|
value = func(self, *args, **kwargs)
|
|
|
|
getattr(self, attr)[key] = value
|
|
|
|
except AttributeError:
|
|
|
|
value = func(self, *args, **kwargs)
|
|
|
|
setattr(self, attr, {key: value})
|
|
|
|
return value
|
2014-05-08 16:59:35 +00:00
|
|
|
return cached_func
|