python2和python3的语法改变与调整_Python 2.x和3.x中的有效语法是否引发异常?

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]

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")

解决方案

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.

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")

Now you can use:

reraise(BarException, BarException(e), sys.exc_info()[2])

without further testing for a Python version.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值