[Python-ideas] for/else syntax

Gerald Britton gerald.britton at gmail.com
Sat Oct 3 20:35:58 CEST 2009

Looking over this all again, it seems to me that the main request
would be for a more explicit statement in the documentation. Something

"When the items are exhausted (which is immediately when the sequence
is empty), the suite in the else clause, if present, is executed, and
the loop terminates.  Note: The suite in the else clause will be
executed unless the iteration is terminated with a break or return, or
raises an exception that is not handled or does not return."

Probably it could use some word-smithing, but is that the basic idea?

One thing I DO like about the construct, though, is it makes it more
apparent what code belongs together.  e.g.

for x in y:
  # suite 1
  # suite 2

It should be obvious that suite 2 belongs with the for statement in
some way.  OTOH:

for x in y:
  # suite 1

# suite 2

You can't immediately see that suite 2 is related to the for
statement.  You might think it is completely independent which could
lead to erroneous results if you modified it without keeping the
for-loop context in mind.

On Sat, Oct 3, 2009 at 1:13 PM, Masklinn <masklinn at masklinn.net> wrote:
> On 3 Oct 2009, at 18:19 , Ron Adam wrote:
>> Yuvgoog Greenle wrote:
>>> Document it as much as you want but the "else" doesn't hint or clue as
>>> to whether it catches breaks or is skipped by them.
>>> The next problem's gonna be at midnight when you're reading code and
>>> asking yourself "hmmm, for, blah blah, else, hmm oh yeah, else-break,
>>> so this else occurs whenever there's a break."
>> True, and that is part of the other 20% I expect the documentation would't
>> help.
>> The only solution to that that I can think of is to change the esle's in
>> for and while loops to for/then and while/then in Python 5.0.
> That would yield
>    for val in vals:
>        if cond(val):
>            break
>        # processing
>    then:
>        # more stuff
> how does it make the "alternate" clause being skipped in case of break any
> clearer?
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

Gerald Britton

More information about the Python-ideas mailing list