for what are for/while else clauses

Alex Martelli aleaxit at yahoo.com
Sun Nov 16 09:51:03 EST 2003


Michele Simionato wrote:

> I personally consider the "else" clause a wart of Python.

I think it depends on what statements we're talking about, but, yes, 
restricting the discussion to for/else and while/else (if/else and 
try/except/else being very different) I understand why you would.

> I never remember exactly what it is doing, and I have to look at the

I haven't had the problem, myself, but I have seen others believe that the 
else clause would run if the body was never run (for on an empty sequence, 
while on a condition that's false since the first check), as in 
(hypothetically)

for item in bought:
    print 'Bought item', item
else:
    print "No items were bought"

being short for

if bought:
    for item in bought:
        print 'Bought item', item
else:
    print "No items were bought"

which might make sense (if bought were a non-reiterable, the if/else 
construct has problems while the imaginary interpretation of the for/else 
one would still work just fine).  In this way, Python's for/else and 
while/else do fail the least-astonishment test for at least some learners
(taking "else" to mean "no break was executed in the body" is hardly
obvious or most particularly "the only obvious" interpretation).

> manual each time; moreover I don't see it giving any significant advantage
> to the language (other languages live very well without). So, I would be

The fact that other languages lack a construct isn't necessarily 
significant, of course -- most lack, e.g., classes as first-class objects, 
yet Python's vastly better for having them.  Still, it is indeed arguable
that for/else buys you little -- just a flag setting and checking when you
do use it, i.e., at most.

> happy to have it removed, even if I am sure it will never happen :-(

Right, it's unlikely -- I haven't it seen proposed as a candidate to go
away in 3.0.

> Am I the only one who think so?

Probably not; even though on the whole I disagree, I don't consider your
position at all "strange", nor my opposition particularly strong, therefore 
I suspect that many at least mildly agree with you.

The classic homework one should do when considering a language
construct is "how is it used in the standard library".  Have you examined
the uses of for/else and while/else there?


Alex





More information about the Python-list mailing list