[Python-ideas] for/else statements considered harmful

Mike Meyer mwm at mired.org
Thu Jun 7 17:30:11 CEST 2012


On Thu, 07 Jun 2012 06:52:49 -0700
Ethan Furman <ethan at stoneleaf.us> wrote:
> I think the main problem with the current while/else, for/else is 
> two-fold: 1) we have two failure states (empty from the start, and 
> desired result not met), and 2) even though the else is more similar to 
> the else in try/except/else, it is formatted *just like* the if/else.

I'd say we have 1.5 failure states, because the desired result is not
met in both cases. In my experience, the general case (that else
handles) is more common than the special case of the iterator being
empty.

> Perhaps the solution is to enhance for and while with except?
> 
>     sock = lsock.accept()
>     for chunk in iter(partial(sock.recv, 4096), ''):
>         pass # do something with the chunk
>     except:
>         pass # no data recieved before client hangup!
>     else:
>         pass # wrap-up processing on chunks

Calling it "wrap-up processing" seems likely to cause people to think
about it as meaning "finally". But if the else clause is not executed
if the except clause is (as done by try/except/else), then there's no
longer an easy way to describe it.

It seems like adding an except would change the conditions under which
the else clause is executed (unlike try/except/else), as otherwise
there's no easy way capture the current behavior, where else is
executed whenever there are no chunks left to process. But that kind
of things seems like a way to introduce bugs.

       <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/
Independent Software developer/SCM consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list