I have a function called runquery
that makes calls to a database and then yields the rows, one by one. I wrote a memoize decorator (or more accurately, I just stole
Similar to the other answers, but simpler if you know that f
is a generator:
def memoized_generator(f):
cache = {}
@functools.wraps(f)
def wrapper(*args, **kwargs):
k = args, frozenset(kwargs.items())
it = cache[k] if k in cache else f(*args, **kwargs)
cache[k], result = itertools.tee(it)
return result
return wrapper