Re: [Python-ideas] for/except/else

On 01.03.2017 12:56, Steven D'Aprano wrote:
On Wed, Mar 01, 2017 at 10:37:17AM +0100, Wolfgang Maier wrote:
Now here's the proposal: allow an except (or except break) clause to follow for/while loops that will be executed if the loop was terminated by a break statement.
Let me see if I understand the proposal in full. You would allow:
for i in (1, 2, 3): print(i) if i == 2: break except break: # or just except assert i == 2 print("a break was executed") else: print("never reached") # this is never reached print("for loop is done")
as an alternative to something like:
broke_out = False for i in (1, 2, 3): print(i) if i == 2: broke_out = True break else: print("never reached") # this is never reached if broke_out: assert i == 2 print("a break was executed") print("for loop is done")
correct.
I must admit the suggestion seems a little bit neater than having to manage a flag myself, but on the other hand I can't remember the last time I've needed to manage a flag like that.
And on the gripping hand, this is even simpler than both alternatives:
for i in (1, 2, 3): print(i) if i == 2: assert i == 2 print("a break was executed") break else: print("never reached") # this is never reached print("for loop is done")
Right, that's how you'd likely implement the behavior today, but see my argument about the two alternative code branches not ending up together at the same level of indentation.
There are some significant unanswered questions:
- Does it matter which order the for...except...else are in? Obviously the for block must come first, but apart from that?
Just like in try/except/else, the order would be for (or while)/except/else with the difference that both except and else would be optional.
- How is this implemented? Currently "break" is a simple unconditional GOTO which jumps past the for block. This will need to change to something significantly more complex.
Yeah, I know that's why I listed this under cons.
- There are other ways to exit a for-loop than just break. Which of them, if any, will also run the except block?
None of them (though, honestly, I cannot think of anything but exceptions here; what do you have in mind?)
participants (1)
-
Wolfgang Maier