Can I memoize a Python generator?

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

    from itertools import tee
    
    sequence, memoized_sequence = tee (sequence, 2)
    

    Done.

    It is easier for generators because the standard lib has this "tee" method!

提交回复
热议问题