[Python-ideas] for/else syntax
ars at iki.fi
Thu Oct 1 13:00:21 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
I must say that calling for ... else "somewhat unintuitive" is the
understatement of the year. The analogy with if ... else leads further
astray than Odysseus.
The feature itself is not bad. It's just that it is misnamed.
I did a quick poll at the office and at IRC, five people in total, with
2-8 years of Python experience. Two had never heard of the for..else
-construct; one had heard that it exists and two know about it but have
never used it. Three uninitiated, in other words.
All three gave similar replies: if the loop is not executed or the
variable is not iterable, then the else-branch is executed. Here are their
reactions, when they learned how it really works:
* "It should be called for..then" (or for..finally)
* "WHAT. No f** way. Completely unintuitive"
* "I'd hate whoever wrote that code"
These people are actual Python developers, not some newbies. And I
completely agree with them. I've only once seen for...else in the wild and
never used it myself.
To add further insult to the naming injury, the else branch suffers from
the fact that 99.9% of the time, the for-loop contains an if:
for x in xs:
# more stuff
My code pattern matching algorithm reads that as an indentation error. An
else matches if so many times more often that decoding for..else requires
I don't want the feature to be removed or even renamed (at least before
Python 4). But the feature *is* badly named and unintuitive.
[ Antti Rasinen <*> ars at iki.fi ]
More information about the Python-ideas