fun with nested loops

Steven D'Aprano steve+comp.lang.python at
Thu Sep 1 21:04:01 EDT 2011

Daniel wrote:

> That's the form the specification is in, and it makes sense and is
> very readable.
> 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
> That format is fine, everyone involved can understand it, even the
> people in charge.

Well good for them, because I sure as hell don't understand it. To me,
that's exactly the sort of thing that Guido was worried about when he
rejected the idea of named labels. I'd need to sit down and trace a few
loops by hand to grasp it. I wonder how new people coming into the project
find it?

Personally, I consider two nested loops right on the boundary of my "magic
number seven, plus or minus two" short term memory[1]. I prefer to chunk
code into functions so that I can ignore details of the inner loops while
reasoning about the outer loops, and vice versa. If you feel different,
then I'm not being sarcastic when I say "good for you".

If you require a 1:1 correspondence between your code and your pseudo-code
specification, then maybe Python isn't the right language for this task.

Ruby is very Python-like, and has labelled loops. Perl and PHP less so, but
can also be quite readable with some discipline. You could also check out
Cobra -- their website is down just at the moment, so I can't check whether
it has labelled loops.

[1] Not really magic, and probably more like 4±2.


More information about the Python-list mailing list