在python中深度复制生成器 [英] deep-copying a generator in python

查看:119
本文介绍了在python中深度复制生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用生成器函数,说:

I'm using a generator function, say:

def foo():
    i=0
    while (i<10):
         i+=1
         yield i

现在,我想选择在多次迭代后复制生成器的选项,以便新副本将保留内部状态(在示例中将具有相同的"i"),但现在将独立于原始状态(即遍历副本不应更改原始副本.)

Now, I would like the option to copy the generator after any number of iterations, so that the new copy will retain the internal state (will have the same 'i' in the example) but will now be independent from the original (i.e. iterating over the copy should not change the original).

我尝试使用copy.deepcopy,但出现错误:

I've tried using copy.deepcopy but I get the error:

 "TypeError: object.__new__(generator) is not safe, use generator.__new__()"   

很明显,我可以使用带有计数器的常规函数​​来解决此问题. 但是我真的在寻找使用生成器的解决方案.

Obviously, I could solve this using regular functions with counters for example. But I'm really looking for a solution using generators.

推荐答案

我可以想到三种情况:

  • Generator没有副作用,您只希望能够回顾已捕获的结果.您可以考虑使用缓存的生成器,而不是真正的生成器.您也可以共享缓存的生成器,并且如果有任何客户端走到您尚未去过的项目,它将继续前进.这类似于tee()方法,但是生成器/缓存本身具有tee功能,而不是要求客户端执行.

  • Generator has no side effects, and you just want to be able to walk back through results you've already captured. You could consider a cached generator instead of a true generator. You can shared the cached generator around as well, and if any client walks to an item you haven't been to yet, it will advance. This is similar to the tee() method, but does the tee functionality in the generator/cache itself instead of requiring the client to do it.

Generator具有副作用,但没有历史记录,您希望能够在任何地方重新启动.考虑将其写为协程,您可以在其中传递值以从任何位置开始时间.

Generator has side effects, but no history, and you want to be able to restart anywhere. Consider writing it as a coroutine, where you can pass in the value to start at any time.

生成器具有副作用和历史记录,这意味着生成器在G(x)的状态取决于G(x-1)的结果,因此您不能仅将x传递回给它从任何地方开始.在这种情况下,我认为您需要更加详细地说明您要尝试执行的操作,因为结果不仅取决于生成器,还取决于其他数据的状态.在这种情况下,也许有更好的方法.

Generator has side effects AND history, meaning that the state of the generator at G(x) depends on the results of G(x-1), and so you can't just pass x back into it to start anywhere. In this case, I think you'd need to be more specific about what you are trying to do, as the result depends not just on the generator, but on the state of other data. Probably, in this case, there is a better way to do it.

这篇关于在python中深度复制生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆