[Python-3000] else-clause on for-loops

Nicola Larosa nico at tekNico.net
Fri Mar 24 09:36:37 CET 2006


Ian Bicking:
>>> When I was just first learning Python I thought this would work:
>>> 
>>>    for item in select_results:
>>>        ...
>>>    else:
>>>        ... stuff when there are no items ...
>>>
>>> But it doesn't work like that.

Brett Cannon:
>> I have to admit that is what I initially thought as well.  I think it
>> is because when I read 'else' I viewed it as an alternative if the
>> clause it was attached to didn't happen (ala an 'if' statement).

Steven Bethard:
> Yeah, I use for-else occasionally, and I know how it works in Python,
> but every time I want to special-case the empty iterable case, I still
> have to remind myself that the else-clause doesn't do what I want it
> to.

The same for me. I sometimes may have had a need for the current semantics
of the else after loops, but I don't remember it; on the other hand, I have
had a use for the no-iteration case a number of times. Somehow I find it
hard to stick into my mind that's not what it means.


> There was talk previously_ about removing the else clause on for-loops
> (and while-loops).  One possibility would be to change the else-clause
> to behave as expected above (i.e. only executed when the loop fails to
> iterate over any items).

I'd like that. Of course it would break compatibility with the past, and
may cause subtle bugs; the advantages would surpass the drawbacks, in my
case, since I rarely use the current semantics, if at all.

-- 
Nicola Larosa - http://www.tekNico.net/

Life [...] is a tale told by an idiot, full of sound and fury,
signifying nothing. -- William Shakespeare, MacBeth
Life is like the chicken ladder: short and full of shit. -- Anonymous



More information about the Python-3000 mailing list