如何模仿Python 3的提升...从Python 2? [英] How to imitate Python 3's raise ... from in Python 2?

查看:179
本文介绍了如何模仿Python 3的提升...从Python 2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3具有整洁的

Python 3 has the neat

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

语法,允许提高后续异常而不会丢失上下文。在Python 2中我可以想出的最好的类比是

syntax which allows raising a followup exception without loosing context. The best analogy I could come up with in Python 2 is

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

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

where the (e,'') is an ugly hack to have the original exception's name included in the message. But isn't there a better way?

推荐答案

有一个 raise_from .org / quickstart.htmlrel =nofollow> python-future ;只需安装它

pip install future

并导入使用

from future.utils import raise_from
# or: from six import raise_from

class FileDatabase:
    def __init__(self, filename):
        try:
            self.file = open(filename)
        except IOError as exc:
            raise_from(DatabaseError('failed to open'), exc)



更新



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

UPDATE

The compatibility package six also supports raise_from, from version 1.9 (released in 2015). It is used in the same manner as above.

这篇关于如何模仿Python 3的提升...从Python 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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