Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 

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] 

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?

like image 503
Tobias Kienzler Avatar asked Dec 05 '14 14:12

Tobias Kienzler


People also ask

Can a program written in Python 3 run in Python 2?

Python 2.6 includes many capabilities that make it easier to write code that works on both 2.6 and 3. As a result, you can program in Python 2 but using certain Python 3 extensions... and the resulting code works on both.

Is Python 2 and 3 the same?

Python 3 has an easier syntax compared to Python 2. A lot of libraries of Python 2 are not forward compatible. A lot of libraries are created in Python 3 to be strictly used with Python 3. Python 2 is no longer in use since 2020.

How do I convert Python2 to Python3?

We can convert Python2 scripts to Python3 scripts by using 2to3 module. It changes Python2 syntax to Python3 syntax. We can change all the files in a particular folder from python2 to python3.


1 Answers

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 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) 

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.

like image 154
tutuDajuju Avatar answered Oct 10 '22 01:10

tutuDajuju