Mercurial > hg > ltpdarepo
view src/ltpdarepo/memoize.py @ 171:f1cc11dc09b7
Reflect markup changes into doctests.
author | Daniele Nicolodi <daniele@grinta.net> |
---|---|
date | Sun, 06 Nov 2011 23:15:25 +0100 |
parents | c812c3020b63 |
children | fbab144c296c |
line wrap: on
line source
import functools class memoize(object): """Decorator that caches a function's return value each time it is called. """ def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: value = self.func(*args) self.cache[args] = value return value except TypeError: # uncachable. 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__ def __get__(self, obj, objtype): """support instance methods""" return functools.partial(self.__call__, obj)