带有finally子句的try块中不允许python 2.4的yield的解决方法
我被困在 python2.4 上,所以我无法将 finally 子句与生成器或 yield 一起使用。有什么办法可以解决这个问题吗?
我找不到任何关于如何在 python 2.4 中解决此限制的提及,并且我不太喜欢我想到的解决方法(主要涉及 __del__ 并试图确保它在合理的时间内运行)不是很有吸引力。
I'm stuck on python2.4, so I can't use a finally clause with generators or yield
. Is there any way to work around this?
I can't find any mentions of how to work around this limitation in python 2.4, and I'm not a big fan of the workarounds I've thought of (mainly involving __del__
and trying to make sure it runs within a reasonable time) aren't very appealing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以复制代码以避免finally块:
变成:(
我没有在Python 2.4上尝试过这个,您可能必须查看sys.exc_info而不是re-raise 语句,如
raise sys.exc_info[0], sys.exc_info[1], sys .exc_info[2]
。)You can duplicate code to avoid the finally block:
Becomes:
(I've not tried this on Python 2.4, you may have to look at sys.exc_info instead of the re-raise statement above, as in
raise sys.exc_info[0], sys.exc_info[1], sys.exc_info[2]
.)当生成器实例被简单放弃(垃圾收集)时,保证调用的唯一代码是其局部变量的 __del__ 方法(如果外部不存在对这些对象的引用)和弱引用的回调到它的局部变量(同上)。我推荐弱引用路径,因为它是非侵入性的(您不需要带有
__del__
的特殊类——只需任何可弱引用的东西)。例如:这会根据需要打印
finis!
。The only code that's guaranteed to be called when a generator instance is simply abandoned (garbage collected) are the
__del__
methods for its local variables (if no references to those objects exist outside) and the callbacks for weak references to its local variables (ditto). I recommend the weak reference route because it's non-invasive (you don't need a special class with a__del__
-- just anything that's weakly referenceable). E.g.:this does print
finis!
, as desired.