How to imitate Python 3's raise … from in Python 2?

十年热恋 提交于 2019-12-03 23:59:12

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

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.

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

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!