[Python-ideas] for/else syntax

Steven D'Aprano steve at pearwood.info
Sat Oct 3 03:46:24 CEST 2009


On Sat, 3 Oct 2009 11:18:44 am Carl Johnson wrote:

> I don't mean to pick on Gerald, but he got the meaning of for/else
> dead wrong *in the middle of a debate about for/else*. This shows
> that even experienced Pythoneers who read Python-ideas can be
> confused about the meaning of for/else. Using it in production code 
> means leaving a trap for the programmers who come after you and read
> your code to get confused and create a bug. Yes, when the others turn
> your working use of for/else into a bug, it's their fault for not
> reading the tutorial more closely so as not get confused by it, but
> ultimately no matter how much you blame the user, that won't stop the
> next guy who uses your code from misunderstanding it.

Damn straight it's their fault. I hope you're not suggesting that people 
shouldn't use any feature that might be misunderstood by lazy, ignorant 
or stupid developers?


> The best solution to this inherent confusingness is to leave bare
> for/else alone for the foreseeable future, but to add a less
> confusing synonym for this feature. I propose "else not break:"
> although "elif not break:" is good too. 

You can already do this today, with no change to the compiler, using 
only a slightly different syntax to that suggested: 

for i, j in enumerate(something):
    # suite
    i += 1
else:  # if not break
    i = 0


Best of all, it's an extensible syntax, so there's no need for 
bike-shedding arguments about whether it should be spelled "not break" 
or "no break" or "didn't break" or "only if loop ended normally". All 
of these variants, and more, are accepted:

for i, j in enumerate(something):
    # suite
    i += 1
else:  # no break occurred and so the loop ended normally
    i = 0





-- 
Steven D'Aprano



More information about the Python-ideas mailing list