[Python-ideas] Break multiple loop levels

Chris Angelico rosuav at gmail.com
Sat May 11 22:50:07 EDT 2019


On Sun, May 12, 2019 at 12:43 PM David Mertz <mertz at gnosis.cx> wrote:
>
> Terry reminds me of a common case I encounter that cannot be transformed into a loop over itertools.product(). E.g.
>
> for main in stuff:
>     if thing_about(main):
>         for detail in more_stuff(stuff, main):
>             if seen_enough(detail):
>                 # break to outer somehow
>     else:
>         for detail in different_stuff():
>             if seen_enough(detail):
>                 # break to outer somehow
>

For that kind of loop, there's a different problem, which is the
duplication. So I would start by rewriting that as:

for main in stuff:
    if thing_about(main):
        details = more_stuff(stuff, main)
    else:
        details = different_stuff()
    for detail in details:
        if seen_enough(detail):
            ...

I'm not sure what you mean by "break to outer somehow", though, so I
don't know what you're actually needing here. Concrete examples would
help.

ChrisA


More information about the Python-ideas mailing list