[Python-Dev] PEP for allowing 'raise NewException from None'
ethan at stoneleaf.us
Fri Jan 27 04:19:45 CET 2012
Title: Interpreter support for concurrent programming
Author: Ethan Furman <ethan at stoneleaf.us>
Type: Standards Track
One of the open issues from PEP 3134 is suppressing context: currently
there is no way to do it. This PEP proposes one.
There are two basic ways to generate exceptions: 1) Python does it
(buggy code, missing resources, ending loops, etc.); and, 2) manually
(with a raise statement).
When writing libraries, or even just custom classes, it can become
necessary to raise exceptions; moreover it can be useful, even
necessary, to change from one exception to another. To take an example
from my dbf module:
value = int(value)
Whatever the original exception was (ValueError, TypeError, or something
else) is irrelevant. The exception from this point on is a DbfError,
and the original exception is of no value. However, if this exception
is printed, we would currently see both.
Several possibilities have been put forth:
- raise as NewException()
Reuses the 'as' keyword; can be confusing since we are not really
reraising the originating exception
- raise NewException() from None
Follows existing syntax of explicitly declaring the originating
- exc = NewException(); exc.__context__ = None; raise exc
Very verbose way of the previous method
- raise NewException.no_context(...)
Make context suppression a class method.
All of the above options will require changes to the core.
I proprose going with the second option:
raise NewException from None
It has the advantage of using the existing pattern of explicitly setting
raise KeyError() from NameError()
but because the 'cause' is None the previous context is discarded.
There is a patch to this effect attached to Issue6210
This document has been placed in the public domain.
More information about the Python-Dev