speendo speendo - 10 days ago 7
Python Question

Raise exception in python 2.x and 3.x

How can I port this code to Python 3 so that it would run in both, Python 2 and Python3?

raise BarException, BarException(e), sys.exc_info()[2]


(copied from http://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-python-3/)

Bonus question

Does it make sense to do something like

IS_PYTHON2 = sys.version_info < (3, 0)

if IS_PYTHON2:
raise BarException, BarException(e), sys.exc_info()[2]
# replace with the code that would run in Python 2 and Python 3 respectively
else:
raise BarException("Bar is closed on Christmas")

Answer

You'll have to resort to using exec() because you cannot use the 3-argument syntax in Python 3; it'll raise a syntax error.

As always the six library already has you covered, ported to not depend on other six definitions their version looks like this:

import sys

if sys.version_info[0] == 3:
    def reraise(tp, value, tb=None):
        if value is None:
            value = tp()
        if value.__traceback__ is not tb:
            raise value.with_traceback(tb)
        raise value

else:    
    exec("def reraise(tp, value, tb=None):\n    raise tp, value, tb\n")

Now you can use:

reraise(BarException, BarException(e), sys.exc_info()[2])

without further testing for a Python version.