如何从Python 2中模仿Python 3的提升?

时间:2021-07-14 18:24:15

Python 3 has the neat

Python 3具有简洁的特性

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

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

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

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

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?

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

2 个解决方案

#1


13  

There's a raise_from in python-future; simply install it

在python-future中有一个原因;简单地安装它

pip install future

and import to use

和导入使用

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)

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.

兼容包6还支持来自1.9版本(2015年发布)的raise_from。它的使用方式与上面相同。

#2


3  

Instead of using six.raise_from, try to use six.reraise, as explained in this page:

而不是使用6。raise_from,尝试使用6。如本页所述,请重播:

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

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)

#1


13  

There's a raise_from in python-future; simply install it

在python-future中有一个原因;简单地安装它

pip install future

and import to use

和导入使用

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)

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.

兼容包6还支持来自1.9版本(2015年发布)的raise_from。它的使用方式与上面相同。

#2


3  

Instead of using six.raise_from, try to use six.reraise, as explained in this page:

而不是使用6。raise_from,尝试使用6。如本页所述,请重播:

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

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)