Breaking/continuing out of multiple loops

A 50-line loop body and eight levels of indentation (assuming this is inside a function) and this is the good version? Having a multi-break won’t didn’t fix that. All the complexity in that code stems from trying to do ad-hoc relational querying with imperative code, at the same time as pre- and post-processing. You should compute all the game stats up front unconditionally, filter out the ones you don’t want separately after the fact, and only then “do stuff”.

In very broad strokes, this is more like what I would expect that code to look like:

def compute_all_stats(leagues: Iterable[League]) -> Iterator[GameStat]:
    # this could probably be improved with itertools
    for league in leagues:
        for player in league:
            for season in player.seasons:
                for game_stats in season:
                    yield process_game_stats(game_stats)

def filter_stats(stats: Iterable[GameStat]) -> list[GameStat]:
    result = []
    # filter out ones you don't want here, maybe even use a real database
    # to help make real queries -- SQLite is built right in to Python
    return result

all_stats = compute_all_stats()

filtered_stats = filter_stats(all_stats)

for stat in filtered_stats: 
    do_stuff(stat)

It’s fewer lines, much less indentation, and congratulations, now you have some simpler, smaller functions that you can actually unit test in isolation.

3 Likes