如何模仿蟒蛇3的提升...来自 Python 2?



Python 3 有整洁的

try:
    raise OneException('sorry')
except OneException as e:
    # after a failed attempt of mitigation:
    raise AnotherException('I give up') from e

允许在不丢失上下文的情况下引发后续异常的语法。我在 Python 2 中能想到的最好的类比是

raise AnotherException((e,'I give up')), None, sys.exc_info()[2]

其中(e,'')是一个丑陋的黑客,将原始异常的名称包含在消息中。但是没有更好的方法吗?

python-future中有一个raise_from;只需安装它

pip install future

并导入使用

from future.utils import raise_from
# or: from six import reraise as raise_from
class FileDatabase:
    def __init__(self, filename):
        try:
            self.file = open(filename)
        except IOError as exc:
            raise_from(DatabaseError('failed to open'), exc)

更新

兼容包六也支持 raise_from ,从版本 1.9(2015 年发布)。它的使用方式与上述相同。

不要使用

six.raise_from,而是尝试使用 six.reraise,如本页所述:

http://python-future.org/compatible_idioms.html

from six import reraise as raise_ 
# or from future.utils import raise_
traceback = sys.exc_info()[2]
raise_(ValueError, "dodgy value", traceback)

最新更新