dosage/dosagelib/decorators.py

31 lines
1,018 B
Python
Raw Normal View History

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 = {}
def __call__(self, *args):
"""Lookup and return cached result if found. Else call stored
function with given arguments."""
try:
return self.cache[args]
except KeyError:
self.cache[args] = value = self.func(*args)
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__