为什么发电机不能腌制?
Python 的 pickle(我在这里说的是标准 Python 2.5/2.6/2.7)不能 pickle 锁、文件对象等。
它也不能 pickle 生成器和 lambda 表达式(或任何其他匿名代码),因为 pickle 实际上只存储名称引用。
对于锁和依赖于操作系统的功能,不能 pickle 它们的原因是显而易见且有意义的。
但是为什么你不能pickle生成器?
注意:只是为了清楚起见——我对根本原因感兴趣(或设计决策中的假设和选择) 为什么,而不是“因为它会给你一个 Pickle 错误”。
我意识到这个问题有点宽泛,所以这里有一个经验法则来决定你是否回答它:“如果提出这些假设,或者允许的发电机类型在某种程度上受到更多限制,酸洗发电机会再次工作吗?”
Python's pickle (I'm talking standard Python 2.5/2.6/2.7 here) cannot pickle locks, file objects etc.
It also cannot pickle generators and lambda expressions (or any other anonymous code), because the pickle really only stores name references.
In case of locks and OS-dependent features, the reason why you cannot pickle them is obvious and makes sense.
But why can't you pickle generators?
Note: just for clarity -- I'm interested in the fundamental reason (or assumptions and choices that went into that design decision) why, not in "because it gives you a Pickle error".
I realize the question's a bit wide-aimed, so here's a rule of thumb of whether your answered it: "If these assumptions were raised, or the type of allowed generator somehow more restricted, would pickling generators work again?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有很多关于此的信息。有关该问题的“官方说法”,请阅读(已关闭)Python bugtracker 问题。
做出该决定的人之一详细说明了核心推理 此博客:
并提到了两个建议的解决方法:
There is lots of information about this available. For the "official word" on the issue, read the (closed) Python bugtracker issue.
The core reasoning, by one of the people who made the decision, is detailed on this blog:
And two suggested workarounds are mentioned:
实际上可以,具体取决于实施情况。 PyPy 和 Stackless Python两者都允许这样做(无论如何在某种程度上):
在 CPython 中也可以创建一个 迭代器对象来模拟可选取的生成器。
You actually can, depending on the implementation. PyPy and Stackless Python both allow this (to some degree anyway):
In CPython it's also possible to create an iterator object to simulate a pickable generator.