[Python-ideas] for/else syntax
Stephen J. Turnbull
stephen at xemacs.org
Fri Oct 2 07:47:26 CEST 2009
Yuvgoog Greenle writes:
> 1. Not allowing a for loop that has no "break" to have an "else". Just like
> "else" isn't allowed when there isn't an "except" in the "try". There really
> is no excuse, justification or sense in a "for" loop that has no "break" yet
> has an "else".
+1. File an RFE against PyLint for sure, and against Python too.
That's a *great* idea!
Bikeshedding follows.
> Antti's experiment got me asking, you can try this as well. Ask a person who
> knows python the following questions:
> Question #1: Do you know what happens when an "else" appears after a "for"
> loop?
> if they answer yes then say nevermind.
Er, no. It's more important if what people "know" is wrong than if
naive guesses are wrong.
> otherwise: continue to question #2.
> Question #2: When would the code in the "else" block execute? If you don't
> know, it's ok to guess.
I would fire a programmer who gave an answer.<0.5 wink> He might do
the same in his own code or in a review of someone else's.
> 3. Renaming this construct for py4k wouldn't be too crazy if you use the
> existing reserved words "not" and "break". Look at this code and please note
> that it doesn't need any comments to make it readable (as opposed to Nick's
> example, no offence):
Nick's example is far more readable IMO. No offense. I can tell you
why, too. In his example, the "else" is immediately preceded by the
"if ... break" suite. Because "break" can only happen once in a loop,
I read the else as the alternative to breaking out. Sloppy, yes, but
since this is the common idiom using for-else, it works for me. :-)
OTOH, "break" is an imperative; "not break" looks like a prohibition
to me, not the target of a branch. You could use "for: ... if not
break:" but that looks ugly to me, and worse requires several tokens
of lookahead to disambiguate from an ordinary if block.
I'll leave it up to GvR to decide whether for-else is "less Pythonic"
than try-except-else.
> And I can even think of a few use cases for having just "break:". This block
> would execute only upon "break" occurring. That way you could have loops
> like this:
>
> for item in list_of_stuff:
> if item.is_awesome():
> break
> break:
> celebrate(list_of_stuff)
You'd need multiple breaks for this to make sense. Else:
for item in list_of_stuff:
if item.is_awesome():
celebrate(list_of_stuff)
break
Some people think that having multiple breaks is bad style.
More information about the Python-ideas
mailing list