[Python-ideas] for/except/else

Steven D'Aprano steve at pearwood.info
Wed Mar 1 06:56:04 EST 2017


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")


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")



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?

- 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.

- There are other ways to exit a for-loop than just break. Which
  of them, if any, will also run the except block?



-- 
Steve


More information about the Python-ideas mailing list