[Python-ideas] except expression

Jan Kaliszewski zuo at chopin.edu.pl
Wed Feb 19 02:37:29 CET 2014


19.02.2014 02:08, Chris Angelico wrote:

> On Wed, Feb 19, 2014 at 11:11 AM, Jan Kaliszewski <zuo at chopin.edu.pl> 
> wrote:
>> IMHO bare except is practically always a very bad practice unless 
>> the
>> exception is immediately re-raised:
>>
>> try:
>>     foo()
>> except:
>>     logger.exception('error:')
>>     raise
>>
>> ...and AFAIK, up to now, nobody proposed any syntax that would make 
>> it
>> possible to re-raise an exception in an except expression.
>>
>> Therefore I believe that bare except should *not* be allowed in
>> except expressions at all.
>
> Reraising inside an expression doesn't make a huge amount of sense. 
> If
> you want to do something and then reraise, what's the value of the
> expression? Go statement-form and make it clearer.

Exactly. That's why I believe bare except should be disallowed in the
expression form.

> But there are legit uses of broad except.

Apart from immediately-re-raising, base except are practically never
a legit use IMHO.

> One is to use the exception
> itself as the value. (See Lib/imaplib.py:568, quoted in the 
> examples.)
> Another is for a "this must never fail" code like repr
> (Lib/asyncore.py:482, the next example). Arguably both should be
> catching Exception, not BaseException;

I believe they should indeed.

> but the recommendation to "log
> it and reraise" should apply just as much to catching Exception as to
> bare-excepting, as an unexpected TypeError or AttributeError could
> indicate a significant bug.

"Log it" -- yes. "Reraise" -- not necessarily for Exception-based ones,
if the are logged, IMHO (see sources of logging, asyncio, tornado...).

> IMO the validity of bare except in an expression should be based on
> readability and bug-magnet possibility, not whether or not the
> exception can be reraised.

Bare except statement is indeed a bug magnet, but:

* it's a legacy that cannot be removed from the language easily,

* at least there are cases when it is valid and also seems to be
   somewhat elegant:

     except:     # *bare* except
         ...
         raise   # *bare* raise

On the other hand, bare except expression would be a bug magnet,
without any legit use cases on horizon.  And, I suppose, the magnet
would be even stronger -- expecially for keystroke-saving-lovers. :)

Let's do not introduce an attractive nuisance whose positive value
is near zero.

Cheers.
*j



More information about the Python-ideas mailing list