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 })
start_response
function in some context, maybe show an example where you would call it? – Evalynevantry/except
? – Imagerystart_response
is part of the WSGI spec. See PEP-333. WSGI apps call start_response when they, well, want to start a response. Ifexc_info
is given then that is the WSGI app's signal that the app code encountered an exception, and the WSGI server should do something with it such as printing an error. In my case I want to raise the error if headers have already been sent out. See python.org/dev/peps/pep-0333/#the-start-response-callable – Flyblownsix.reraise()
– Danczyksix
? I asked about it here: #32319817 – Similar