[Python-ideas] for/else syntax

Carl Johnson cmjohnson.mailinglist at gmail.com
Sat Oct 3 03:18:44 CEST 2009


Those who believe that the for/else construct is sufficiently clear,
please read this email again:

Gerald Britton:

> I can't imagine why I'm still commenting on this thread, since there
> is no chance that Python will remove the "else" from for/while or put
> conditions on it, but here is an example of a use that has no break
> statement:
>
> for i, j in enumerate(something):
>  # suite
>  i += 1
> else:
>  i = 0
>
> # i == number of things processed
>
> The thing here is, "i" won't be set by the "for" statement if
> "something" is empty.  OTOH, if "something" is non-empty, i >= 1 at
> the end of the for-loop.  Using the "else" clause in this way ensure
> that "i" has the number of things processed at the end of the loop.
>
> To do this without the "else" I have to:
>
> i = 0
> for i, j in enumerate(something):
>  # suite
>  i += 1
> I can't imagine why I'm still commenting on this thread, since there
> is no chance that Python will remove the "else" from for/while or put
> conditions on it, but here is an example of a use that has no break
> statement:
>
> for i, j in enumerate(something):
>  # suite
>  i += 1
> else:
>  i = 0
>
> # i == number of things processed
>
> Does it work?  Sure!  But it moves the setting of "i" outside the
> for-construct, which I personally dislike.

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.

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. Rewriting Gerald's example as

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

# i == number of things processed

makes it 100% smack you in the face obvious that "Oh yeah, this is
going to set i to 0 every time, since there's no break."

In an unrelated but also good idea, it would be nice to be able to do
what Gerald thought he was doing:

for i, j in enumerate(something):
  # suite
  i += 1
else if None: #or some other suitable phrase for "empty"
  i = 0

# i == number of things processed

— Carl



More information about the Python-ideas mailing list