Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write exception reraising code that's compatible with both Python 2 and Python 3?

Tags:

I'm trying to make my WSGI server implementation compatible with both Python 2 and Python 3. I had this code:

def start_response(status, response_headers, exc_info = None):     if exc_info:         try:             if headers_sent:                 # Re-raise original exception if headers sent.                 raise exc_info[0], exc_info[1], exc_info[2]         finally:             # Avoid dangling circular ref.             exc_info = None     elif headers_set:         raise AssertionError("Headers already set!")      headers_set[:] = [status, response_headers]     return write 

...with the relevant part being:

# Re-raise original exception if headers sent. raise exc_info[0], exc_info[1], exc_info[2] 

Python 3 doesn't support that syntax anymore so it must be translated to:

raise exc_info[0].with_traceback(exc_info[1], exc_info[2]) 

Problem: the Python 2 syntax generates a parse error in Python 3. How do I write code that can be parsed by both Python 2 and Python 3? I've tried the following, but that doesn't work:

if sys.version_info[0] >= 3:     raise exc_info[0].with_traceback(exc_info[1], exc_info[2]) else:     eval("raise exc_info[0], exc_info[1], exc_info[2]; 1", None, { 'exc_info': exc_info }) 
like image 798
Hongli Avatar asked Jan 24 '13 14:01

Hongli


People also ask

Are Python 2 and 3 compatible with each other?

While you can make Python 2.5 work with Python 3, it is much easier if you only have to work with Python 2.7. If dropping Python 2.5 is not an option then the six project can help you support Python 2.5 & 3 simultaneously ( python -m pip install six ).

How do I run Python 2 code in Python 3?

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.

How do I know if Python3 is compatible?

You can use Pycharm IDE for this. Just open the python files in the pycharm editor, it will show warnings if the code is not compatible to Python2 or Python3. Here is the screenshot where it shows print command syntax warning.

How do you create an exception in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.


1 Answers

Can you use six? It exists to solve this very problem.

import six, sys six.reraise(*sys.exc_info()) 

See: https://six.readthedocs.io/index.html#six.reraise

like image 59
Jon-Eric Avatar answered Oct 04 '22 03:10

Jon-Eric