added more decorators

git-svn-id: https://linkchecker.svn.sourceforge.net/svnroot/linkchecker/trunk/linkchecker@3014 e7d03fd6-7b0d-0410-9947-9c21f3af8025
This commit is contained in:
calvin 2006-01-06 15:02:50 +00:00
parent e94c61529b
commit fc5e34b216

View file

@ -143,3 +143,50 @@ def timeit (func, log=sys.stderr):
func(*args, **kwargs)
print >>log, func.__name__, "took %0.2f seconds" % (time.time() - t)
return update_func_meta(newfunc, func)
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):
self.func = func
self.cache = {}
def __call__(self, *args):
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__
class curried (object):
"""
Decorator that returns a function that keeps returning functions
until all arguments are supplied; then the original function is
evaluated.
"""
def __init__(self, func, *a):
self.func = func
self.args = a
def __call__(self, *a):
args = self.args + a
if len(args) < self.func.func_code.co_argcount:
return curried(self.func, *args)
else:
return self.func(*args)