Python2“在一个fi中提升e[0]、e[1]、e[2]和python3版本

2024-04-19 18:41:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现python 3相当于:

raise e[0], e[1], e[2]

看起来像这样:

^{pr2}$

但是我得到了第一个语法错误(在Python3中)或object has no attribute 'with_traceback'(在Python2中)

如何为两个版本编写这些行而不出错?在


Tags: no版本objectwithattributepython3raisehas
2条回答

似乎^{}是你想要的。在

使用在py2和py3中都有效的不同回溯引发异常的示例:

from __future__ import print_function
import sys
import six


def this_should_show_up_in_the_traceback():
    raise ValueError("an exception")

try:
    this_should_show_up_in_the_traceback()
except:
    type, value, tb = sys.exc_info()

print('stashed a traceback for later', type, value, tb)

six.reraise(IndexError, IndexError("other exception"), tb)

根据第节中的PEP 3109 Raising Exceptions in Python 3000兼容性问题

Three-expression raise statements will be converted from

raise E, V, T

to

e = E(V)
e.__traceback__ = T
raise e

在你的例子中

ex = e[0](e[1])
ex.__traceback__ = e[2]
raise ex

相关问题 更多 >