Breaking/continuing out of multiple loops

The obvious fix for that ugly code is to refactor into a function:

def handle_inner_loops(sport):
    for player in all_players:
        for player_tables in all_tables:
            for version in player_tables:
                if condition:
                    # things have gone wrong, bail out early.
                    return
                block()

for sport in all_sports:
    handle_inner_loops(sport)

The solution to “Python needs a way to jump out of a chunk of code” is usually to put the chunk of code into a function, then return out of it.

I don’t know what refactoring approaches you are thinking of, but if you think putting code in a function is “anti-pythonic”, I think you’re going to have a bad time :slight_smile:

Otherwise we can simulate some kinds of goto using a raise:

class MultiBreak(Exception): pass

for sport in all_sports:
    try:
        for player in all_players:
            for player_tables in all_tables:
                for version in player_tables:
                    if condition:
                        # things have gone wrong, bail out early.
                        raise MultiBreak
                    block()
    except MultiBreak:
        pass

The good thing here is that you can see exactly where you are jumping to, and if you need to do some special handling it is easy to replace the pass with the error recovery code.

6 Likes