Can I memoize a Python generator?

后端 未结 4 1158
伪装坚强ぢ
伪装坚强ぢ 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:53

    I realise this is somewhat of an old question, but for those who want a full solution: here's one, based on jsbueno's suggestion:

    from itertools import tee
    from types import GeneratorType
    
    Tee = tee([], 1)[0].__class__
    
    def memoized(f):
        cache={}
        def ret(*args):
            if args not in cache:
                cache[args]=f(*args)
            if isinstance(cache[args], (GeneratorType, Tee)):
                # the original can't be used any more,
                # so we need to change the cache as well
                cache[args], r = tee(cache[args])
                return r
            return cache[args]
        return ret
    

提交回复
热议问题