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.