[Python-ideas] raise EXC from None (issue #6210)

Steven D'Aprano steve at pearwood.info
Sat Oct 22 08:46:25 CEST 2011


Jan Kaliszewski wrote:
> Hello.
> 
> Some time ago I encountered the problem described in PEP 3134 as "Open
> Issue: Suppressing Context" ("this PEP makes it impossible to suppress
> '__context__', since setting exc.__context__ to None in an 'except' or
> 'finally' clause will only result in it being set again when exc is
> raised.").
> 
> An idea that then appeared in my brain was:
> 
>     raise SomeException(some, arguments) from None
> 
> ...and I see the same idea has been proposed by Patrick Westerhoff here:
> http://bugs.python.org/issue6210


I think that stating the syntax is the easy part, actually implementing 
may not be so simple.


> I am +10, as I feel that's intuitive, elegant and status-quo-consistent.
> 
> And what do you think?

I think that it's well past time to fix this wart with the new nested 
exceptions functionality.

+1

(Actually I'm also +10 but I don't want to start vote inflation.)

The wart I'm referring to is that the common idiom of catching one 
exception and raising another is now treated as a bug in the except 
clause even when it isn't:

 >>> def mean(data):
...     try:
...             return sum(data)/len(data)
...     except ZeroDivisionError:
...             raise ValueError('data must be non-empty')
...
 >>> mean([])
Traceback (most recent call last):
   File "<stdin>", line 3, in mean
ZeroDivisionError: int division or modulo by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 5, in mean
ValueError: data must be non-empty


In this case, there is absolutely no reason to expose the fact that 
ZeroDivisionError occurred. That's an implementation detail which is 
irrelevant to the caller. But exposing it complicates the traceback for 
no benefit (since it isn't a bug that needs fixing) and possibly some 
harm (by causing some confusion to the reader).

It also reflects badly on your code: it gives the impression of an 
unhandled bug when it is not.

In my opinion, although the error context functionality is a big 
positive when debugging actual bugs in except clauses, the feature 
should never have been added without a way to suppress the error context.


-- 
Steven



More information about the Python-ideas mailing list