flow control and nested loops

kj no.email at please.post
Fri Sep 25 15:01:47 EDT 2009



In Perl, one can label loops for finer flow control.  For example:

X: for my $x (@X) {
  Y: for my $y (@Y) {
    for my $z (@Z) {
      next X if test1($x, $y, $z);
      next Y if test2($x, $y, $z);
      frobnicate($x, $y, $z);
    }
    glortz($x, $y); 
  }
  splat($x); 
}

What's considered "best practice" in the Python world for this sort
of situation?  The only approach I can think of requires setting
up indicator variables that must be set and tested individually;
e.g.

for x in X:
    next_X = False
    for y in Y:
        next_Y = False
        for z in Z:
            if test1(x, y, z):
                next_X = True
                break
            if test2(x, y, z):
                next_Y = True
                break
            frobnicate(x, y, z)
        if next_X:
            break
        if next_Y:
            continue
        glortz(x, y) 
    if next_X:
        continue
    splat(x) 

Whereas I find the Perl version reasonably readable, the Python
one I find nearly incomprehensible.  In fact, I'm not even sure
that the Python version faithfully replicates what the Perl one is
doing!

Is there a better approach?

TIA!

kynn




More information about the Python-list mailing list