[Python-3000] Announcing PEP 3136

Neil Toronto ntoronto at cs.byu.edu
Tue Jul 3 11:42:09 CEST 2007


Giovanni Bajo wrote:
> On 03/07/2007 9.17, Neil Toronto wrote:
>   
>> Greg Ewing wrote:
>>     
>>> On 30/06/2007 22.54, Matt Chisholm wrote:
>>>
>>>   
>>>       
>>>> I've created and submitted a new PEP proposing support for labels in
>>>> Python's break and continue statements.
>>>>
>>>> http://www.python.org/dev/peps/pep-3136/
>>>>     
>>>>         
>>> -1. Confusing nested loops are best broken out into
>>> separate functions rather than patching over the
>>> problem with features like this.
>>>   
>>>       
>> +1 (not that my vote really counts for much). Breaking logic out into 
>> separate functions can obscure the meaning of an algorithm that is most 
>> naturally implemented with nested loops.
>>     
>
> Do you have a concrete, real-world example?
>   

You pragmatists and your concrete, real-world examples. :p

Anyway, sure: image processing -> binary morphological operators -> 
erode. It's a four-deep nested loop. You pass a binary bitmask (kernel) 
over a binary image, centering it on each pixel. If one bit in the image 
is off that's on in the kernel, you turn off the center pixel in the 
destination. This is the obvious break - it only takes one, so it's 
senseless to keep going in the inner two loops.

Moving the innermost two loops into a new function makes the flow of the 
algorithm less linear and therefore less clear. (Also, the function 
would never be called from anywhere else. How about an inner function? 
That's worse for understandability, IMNSHO.) Other ways of avoiding the 
inner break, such as counting hits, or overwriting the center pixel 
repeatedly, obscure the meaning of the morphological operator.

Granted, Python doesn't usually get used for low-level stuff like this, 
and I'd probably use Numpy array operations in the place of the inner 
two loops, which would be less efficient, but faster. But you were 
asking whether algorithms that are naturally expressed as nested loops 
with breaks exist, and this just happened to be on my hard drive, 
written in Java.

FWIW, I've read Guido's recent rejection of this PEP, but I wanted to 
take up the challenge of showing that these (admittedly rare) use cases 
do exist. A lot of them come from 2D analogues of algorithms that call 
for a break from an inner loop.

Neil



More information about the Python-3000 mailing list