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 })
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 ).
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With