pythonexceptionpython-3.2python-3.3forward-compatibility

How do I gracefully include Python 3.3 from None exception syntax in a Python 3.2 program?


I'm trying to re-raise an exception to give the user better information about the actual error. Python 3.3 includes PEP 409. It adds the raise NewException from None syntax to suppress the context of the original exception.

However, I am targeting Python 3.2. The Python script will parse, but at runtime if it encounters the from None syntax it will produce TypeError: exception causes must derive from BaseException. For example:

try:
    regex_c = re.compile('^{}$'.format(regex)) 
except re.error as e:
    e_msg = 'Regular expression error in "{}"'.format(regex)
    e_reraise = Exception(e_msg)
    # Makes use of the new Python 3.3 exception syntax [from None]
    # to suppress the context of the original exception
    # Causes an additional TypeError exception in Python 3.2
    raise e_reraise from None

Encapsulating raise e_reraise from None in a try just produces an even larger exception stacktrace. A version check doesn't work either, since my python3.3 on Xubuntu 12.10 pulls modules from /usr/lib/python3/dist-packages/* which was is setup for python3.2 modules. (You get a convenient Error in sys.excepthook: which creates a massive traceback.)

Is there a way to use the PEP 409 feature when running in Python 3.3, while silently ignoring it in Python 3.2?


Solution

  • The PEP you linked provides the solution:

    • raise NewException() from None

    Follows existing syntax of explicitly declaring the originating exception

    • exc = NewException(); exc.__context__ = None; raise exc

    Very verbose way of the previous method

    So, you simply have to avoid the new syntax and use the verbose equivalent.

    If you don't want to see the assignments you can put the code into a function:

    def suppress_context(exc):
        exc.__context__ = None
        return exc
    

    And then do:

    raise suppress_context(TheErrorClass())
    

    Edit: as pointed out by Martijn PEP 415 changed this behaviour:

    To summarize, raise exc from cause will be equivalent to:

    exc.__cause__ = cause
    raise exc
    

    Thus, instead of setting __context__ to None you should set __cause__ to None.

    If you really want to use the new syntax, then the only way to do this is to replace sys.excepthook with something that parses the traceback output and removes the the parts that you don't want. But in this case you also must do this:

    try:
        raise error from None
    except TypeError:
        raise error
    

    Then the excepthook should search the traceback and if it should remove the parts related to the raise error from None line. Not a simple task and you end up with more code than the other solution.