Can I memoize a Python generator?

后端 未结 4 1107
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 18:03

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

4条回答
  •  余生分开走
    2021-02-01 18:30

    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
    

提交回复
热议问题