fun with nested loops

Carl Banks pavlovevidence at gmail.com
Thu Sep 1 15:02:45 EDT 2011


On Wednesday, August 31, 2011 8:51:45 AM UTC-7, Daniel wrote:
> Dear All,
> 
> I have some complicated loops of the following form
> 
> for c in configurations: # loop 1
>     while nothing_bad_happened: # loop 2
>         while step1_did_not_work: # loop 3
>             for substeps in step1 # loop 4a
>                 # at this point, we may have to
>                 -leave loop 1
>                 -restart loop 4
>                 -skip a step in loop 4
>                 -continue on to loop 4b
> 
>         while step2_did_not_work: # loop 4b
>             for substeps in step2:
>                 # at this point, we may have to
>                 -leave loop 1
>                 -restart loop 2
>                 -restart loop 4b
>                 ...
>         ...many more loops...
> 
> 
> I don't see any way to reduce these nested loops logically, they
> describe pretty well what the software has to do.
> This is a data acquisition application, so on ever line there is
> a lot of IO that might fail or make subsequent steps useless or
> require a
> retry.
> 
> Now every step could need to break out of any of the enclosing loops.


I feel your pain.  Every language, even Python, has cases where the trade-offs made in the language design make some legitimate task very difficult.  In such cases I typically throw out the guidebook and make use of whatever shameless Perlesque thing it takes to keep things manageable.

In your example you seem like you're trying to maintain some semblance of structure and good habit; I'd it's probably no longer worth it.  Just store the level to break to in a variable, and after every loop check the variable and break if you need to break further.  Something like this, for example:

break_level = 99
while loop1:
    while loop2:
        while loop3:
            if some_condition:
                break_level = (1, 2, or 3)
                break
        if break_level < 3: break
        break_level = 99
    if break_level < 2: break
    break_level = 99


Carl Banks



More information about the Python-list mailing list