for / while else doesn't make sense

Steven D'Aprano steve at pearwood.info
Thu May 19 13:46:53 EDT 2016


On Fri, 20 May 2016 02:31 am, Herkermer Sherwood wrote:

> Most keywords in Python make linguistic sense, but using "else" in for and
> while structures is kludgy and misleading. I am under the assumption that
> this was just utilizing an already existing keyword. Adding another like
> "andthen" would not be good.

If I could steal the keys to Guido's time machine, I would go back in time
and change the for...else and while...else keywords to for...then and
while...then.

Alas, we missed the opportunity for a major backwards-incompatible change.
Python 3.0 is long past, we're up to 3.5 now, 3.6 is in alpha, there's no
way the keyword is going to be changed :-(


> But there is already a reserved keyword that would work great here.
> "finally". It is already a known keyword used in try blocks, but would
> work perfectly here. Best of all, it would actually make sense.

No. for...else doesn't operate like a finally block. The idea of finally is
that it executes no matter what happens[1]. That's completely the opposite
of for...else: the whole point of for...else is that "break" will jump out
of the block without executing the else part.

> Unfortunately, it wouldn't follow the semantics of
> try/except/else/finally.

Exactly.


> Is it better to follow the semantics used elsewhere in the language, or
> have the language itself make sense semantically?

If Python was a younger language with fewer users, less existing code, and
no backwards-compatibility guarantees, I would argue for changing
for...else to for...then. But Python is over 20 years old, has tens or
hundreds of thousands of users, tens of millions of lines of code, and
quite strict backwards-compatibility guarantees.


> I think perhaps "finally" should be added to for and while to do the same
> thing as "else". What do you think?

I think adding "finally" as an alias is just needlessly confusing.

Think of the millions of people who aren't English speakers who nevertheless
had to memorise weird and unintuitive words like "for", "while", "if" etc.
The least we English speakers can do is suck it up and memorise *one* weird
case, "else".






[1] Well, *almost* no matter what. If you pull the power from the computer,
the finally block never gets a chance to run.


-- 
Steven




More information about the Python-list mailing list