Python 2.x和3.x中的有效语法是否引发异常? [英] Valid syntax in both Python 2.x and 3.x for raising exception?

查看:134
本文介绍了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.

这篇关于Python 2.x和3.x中的有效语法是否引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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