fun with nested loops

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at
Thu Sep 1 16:57:39 CEST 2011

Am 01.09.2011 16:05 schrieb Daniel:

> In pseudocode it looks like this, I am using @ to give loops a name:
> @loop1
> for c in configurations:
>      @loop2
>      while not_done:
>          @loop3
>          while step1_did_not_work:
>              @loop4
>              for substeps in step1 # loop 4a
>                  if hopeless(): continue loop1 # run next configuration
>                  if substepsFailed(): restart loop4 # try again
>                  if substepsWorked(): break loop3 # go on to next
> steps, like loop4

let me have a try:

def loop(f):
     def wrapper(*a, **k):
         while True:
                 ret = f(*a, **k):
                 return ret
             except wrapper.restart:
                 continue # next try
             except wrapper.stop:
                 return None
             return ret
     wrapper.restart = type('restart', (Exception,), {})
     wrapper.stop = type('stop', (Exception,), {})
     return wrapper

def level1():
     for c in configurations:

def level2():
     while not_done:

def level3():
     while step1_did_not_work:

def level4a():
     for substeps in step1
         if hopeless: raise level2.stop
         if substepsFailed: raise level4a.restart
         if substepsWorked: return ok

I don't know if I have the levels right, but that should be a way which 
works, without too many indentations.

Another approach could be a decorator which immediately runs the given 
functions, after adding the needed exception classes.


More information about the Python-list mailing list