在带有finally子句的try块中不允许python 2.4的yield的变通办法 [英] Workaround for python 2.4's yield not allowed in try block with finally clause

查看:84
本文介绍了在带有finally子句的try块中不允许python 2.4的yield的变通办法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在python2.4上,所以我不能在generators或yield上使用finally子句.有什么办法可以解决这个问题?

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?

我在python 2.4中找不到关于如何解决此限制的任何提法,而且我也不是我想到的解决方法的忠实拥护者(主要涉及__del__并试图确保其运行)在合理的时间内)不是很吸引人.

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.

推荐答案

您可以复制代码来避免finally块:

You can duplicate code to avoid the finally block:

try:
  yield 42
finally:
  do_something()

成为:

try:
  yield 42
except:  # bare except, catches *anything*
  do_something()
  raise  # re-raise same exception
do_something()

(我尚未在Python 2.4上尝试过此方法,您可能必须查看sys.exc_info而不是

(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].)

这篇关于在带有finally子句的try块中不允许python 2.4的yield的变通办法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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