Python 2.x和3.x中的有效语法是否引发异常?
问题描述:
如何将这段代码移植到Python 3,使其可以同时在Python 2和Python3中运行?
How can I port this code to Python 3 so that it would run in both, Python 2 and Python3?
raise BarException, BarException(e), sys.exc_info()[2]
(从 http://blog.ionelmc.ro/2014 / 08/03 / the-most-mostrated under-feature-in-python-3 / )
奖金问题
进行类似的操作是否有意义
Bonus question
Does it make sense to do something like
IS_PYTHON2 = sys.version_info < (3, 0)
if IS_PYTHON2:
raise BarException, BarException(e), sys.exc_info()[2]
# replace with the code that would run in Python 2 and Python 3 respectively
else:
raise BarException("Bar is closed on Christmas")
答
您将不得不使用 exec()
,因为您无法在Python中使用3参数语法3;
You'll have to resort to using exec()
because you cannot use the 3-argument syntax in Python 3; it'll raise a syntax error.
和往常一样, six
库已经介绍过,移植为不依赖其他 six
定义,它们的版本如下:
As always the six
library already has you covered, ported to not depend on other six
definitions their version looks like this:
import sys
if sys.version_info[0] == 3:
def reraise(tp, value, tb=None):
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
else:
exec("def reraise(tp, value, tb=None):\n raise tp, value, tb\n")
现在您可以使用:
reraise(BarException, BarException(e), sys.exc_info()[2])
,无需进一步测试Python版本。
without further testing for a Python version.