2012-12-12 16:41:29 +00:00
|
|
|
# -*- coding: iso-8859-1 -*-
|
2013-02-11 18:54:50 +00:00
|
|
|
# Copyright (C) 2012-2013 Bastian Kleineidam
|
2012-12-12 16:41:29 +00:00
|
|
|
|
|
|
|
class memoized (object):
|
|
|
|
"""Decorator that caches a function's return value each time it is called.
|
|
|
|
If called later with the same arguments, the cached value is returned, and
|
|
|
|
not re-evaluated."""
|
|
|
|
|
|
|
|
def __init__(self, func):
|
|
|
|
"""Store function and initialize the cache."""
|
|
|
|
self.func = func
|
|
|
|
self.cache = {}
|
|
|
|
|
2013-02-13 16:52:07 +00:00
|
|
|
def __call__(self, *args, **kwargs):
|
2012-12-12 16:41:29 +00:00
|
|
|
"""Lookup and return cached result if found. Else call stored
|
|
|
|
function with given arguments."""
|
|
|
|
try:
|
|
|
|
return self.cache[args]
|
|
|
|
except KeyError:
|
2013-02-13 16:52:07 +00:00
|
|
|
self.cache[args] = value = self.func(*args, **kwargs)
|
2012-12-12 16:41:29 +00:00
|
|
|
return value
|
|
|
|
except TypeError:
|
|
|
|
# uncachable -- for instance, passing a list as an argument.
|
|
|
|
# Better to not cache than to blow up entirely.
|
2013-02-13 16:52:07 +00:00
|
|
|
return self.func(*args, **kwargs)
|
2012-12-12 16:41:29 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
"""Return the function's docstring."""
|
|
|
|
return self.func.__doc__
|
|
|
|
|