Breaking out of nested loops

Paul Sidorsky paulsid at shaw.ca
Sun Jan 13 02:20:32 EST 2002


Steven Majewski wrote:

> That conclusion tends to reinforce my initial reaction to these
> proposals: that the 'problem' is really that deeply nested loops
> in a single procedure is the real 'design error' , not any particular
> syntax. Sometimes it can't be avoided, but I haven't seen a proposal
> for new syntax that is any easier to read than the example above.

I tend to agree that this feature isn't really needed - the flag
approach or isolate-into-a-function approach usually works for me. 
However, such a feature might be reasonable if the "strong" break is
tied to to the loop itself rather than the break statement.  For
example, something like this:

i = 1
while i < 20:
    j = 1
    while trans j < 20:
        if i * j > 200:
            break          # Quits both loops because of trans
        j += 1
    i += 1

Here "trans" is a new keyword or directive that tells Python that a
break in the loop is to be "transparent", i.e. that it will propagate
down to the loop below.  ("yield" could even be used for this purpose as
it sort of makes sense, but that's a pretty gross abuse of the
keyword!)  These could of course be nested to allow multiple-level
break-outs, and intermixed with non-"trans" loops as needed.  

To me, the main advantages with this approach are:

1) 100% backwards compatible.  (It should also work with for loops too.)

2) Explicit - you can tell immediately from looking at the loop
construct what will happen.  You also are stuck with "transparent"
breaks if you choose them, so if you want something more complicated you
have to find a better solution (which, as Steven mentioned, is probably
a good idea anyhow).

3) Maintainable, at least more so than some of the other solutions. 
There's no need to count indentation levels or update labels.  When
adding/removing a loop the only consideration is whether to update the
"transparentness" of other loops in the nest.

Anyhow, I'm really just thinking out loud.  Like I said, I won't
complain if such a feature is never added.

P.S. I keep putting "transparent" in quotes because it doesn't seem to
be the best word for this type of behaviour, but I can't think of a
better one right now.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid at shaw.ca                        http://members.shaw.ca/paulsid/




More information about the Python-list mailing list