[Python-ideas] for/else syntax

Georg Brandl g.brandl at gmx.net
Thu Oct 1 09:48:24 CEST 2009

Yuvgoog Greenle schrieb:
> 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".

I agree that the "else" clause is somewhat unintuitive.  However, it has
its uses and can often replace more awkward constructs.  As such, I would
be -1 on removing it, and -3 on reusing the else clause for some other

> 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.

The block in question is called "empty" in the Django template language,
not "else".  If you look at the discussion that led to its introduction,
you can see confusion with Python's else cited, and the tag was named
"default"/"empty" because of that: http://code.djangoproject.com/ticket/6398

One template language that uses "else" for this case is Jinja (which is
similar in syntax to Django templates, maybe you confused them).  However,
I know that Armin does know how Python's for-else works :)  It is simply not
useful for a (template) language that has no "break", while a "default"
clause is very convenient there.


More information about the Python-ideas mailing list