Add a close() method for generator-iterators, which raises GeneratorExit at the point where the generator was paused. If
the generator then raises StopIteration (by exiting normally, or
due to already being closed) or GeneratorExit (by not catching
the exception), close() returns to its caller. If the generator
yields a value, a RuntimeError is raised. If the generator
raises any other exception, it is propagated to the caller.
close() does nothing if the generator has already exited due to
an exception or normal exit.
Add support to ensure that close() is called when a generator
iterator is garbage-collected.
是的,您可以在生成器中使用
with
语句而不会出现问题。Python将正确处理上下文,因为垃圾收集时生成器将关闭。在在生成器中,
GeneratorExit
异常在生成器被垃圾回收时引发,因为它将在此时关闭:这是PEP 342的一部分,关闭生成器将引发异常。获取一个没有引用的生成器应该始终关闭该生成器,如果Jython没有关闭生成器,我会认为这是一个bug。在
见规范概要第4点和第5点:
唯一需要注意的是,在Jython、IronPython和pypyy中,不能保证垃圾收集器在退出解释器之前运行。如果这对应用程序很重要,可以显式关闭生成器:
^{pr2}$或显式触发垃圾回收。在
如果您的重点是安全性,则可以始终将生成器包装在
contextlib.closing
中-这似乎是最直接的解决方案:事实上,如果是我,我会把函数写成
^{pr2}$确保任何用户都必须将其放入
with
中才能使用它。在相关问题 更多 >
编程相关推荐