[Python-ideas] for/else syntax

Yuvgoog Greenle ubershmekel at gmail.com
Thu Oct 1 03:07:19 CEST 2009


On python-dev the subject of for/else statements came up, so I had to
mention how "ambiguous" the syntax seems to me. By "ambiguous" I meant that
it's not obvious what should happen in the for/else and while/else
constructs (the except/else construct is readable and great imo btw).

Even though it's documented, for me it's a bad construct because it can and
will always be misinterpreted by a non-trivial amount of people seeing it
for the first time. It's unreadable and confusing because the "else" isn't
referring to the "for" it's in reference to the "break". The construct is
only useful in loops with "break" statements, so in pseudo code or human the
"else" would have probably been translated to "if didn't break".

To make things worse, it's not that newcomers will say "hmm, what does this
for/else thing do? lets look at the manual", they will mistakenly assume
they understand what the construct means. For evidence, see the for/else
construct in the django templating language where "else" means the loop
didn't run. The django interpretation IMHO is much more natural because
"else" AFAIK means "otherwise" meaning that statements inside an "else"
block will never be executed if the statements in the previous block were.

To summarize:

whatever:
A
else:
B

looks like it means either A happened or B happened. In python
for/while/else constructs, this doesn't hold.

--yuv

Original Thread: [Python-Dev] Announcing PEP 3136

---------- Forwarded message ----------
From: Terry Reedy <tjreedy at udel.edu>
Date: Thu, Oct 1, 2009 at 2:47 AM
Subject: Re: [Python-Dev] Announcing PEP 3136
To: python-dev at python.org


Yuvgoog Greenle wrote:

> I like how python has a minimalistic and powerful syntax (-1 for the break
> ___ PEP).
>
> Also, I really dislike the for/else ambiguity "butterflies".
>

Properly understood, no ambiguity.

while c:
 x()

is equivalent to hypothetical

label z:
if c:
 x()
 goto: z

So

while c:
 x()
else:
 y()

is equivalent to

label 1:
if c:
 x()
 goto: 1
else"
 y()

The else clause fires (once) if and when the if/while condition evaluates as
false. Break and continue are restricted *unconditional* goto statements,
and so *cannot* trigger an else clause.

In for loops, the implied condition is 'there is another item in the
collection represented by the iterable'.

For any more, move to another list.

Terry Jan Reedy


_______________________________________________
Python-Dev mailing list
Python-Dev at python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
http://mail.python.org/mailman/options/python-dev/ubershmekel%40gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20091001/83e3b63f/attachment.html>


More information about the Python-ideas mailing list