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