"no variable or argument declarations are necessary."

Duncan Booth duncan.booth at invalid.invalid
Mon Oct 3 04:23:41 EDT 2005


Antoon Pardon wrote:

> Well I'm a bit getting sick of those references to standard idioms.
> There are moments those standard idioms don't work, while the
> gist of the OP's remark still stands like:
> 
>   egold = 0:
>   while egold < 10:
>     if test():
>       ego1d = egold + 1
> 

Oh come on. That is a completely contrived example, and besides you can 
still rewrite it easily using the 'standard idiom' at which point it 
becomes rather clearer that it is in danger of being an infinite loop even 
without assigning to the wrong variable.

for egold in range(10):
    while test():
        pass

I find it very hard to believe that anyone would actually mistype ego1d 
while intending to type egold (1 and l aren't exactly close on the 
keyboard), and if they typed ego1d thinking that was the name of the loop 
variable they would type it in both cases (or use 'ego1d += 1') which would 
throw an exception.

The only remaining concern is the case where both ego1d and egold are 
existing variables, or more realistically you increment the wrong existing 
counter (j instead of i), and your statically typed language isn't going to 
catch that either.

I'm trying to think back through code I've written over the past few years, 
and I can remember cases where I've ended up with accidental infinite loops 
in languages which force me to write loops with explicit incremements, but 
I really can't remember that happening in a Python program.

Having just grepped over a pile of Python code, I'm actually suprised to 
see how often I use 'while' outside generators even in cases where a 'for' 
loop would be sensible. In particular I have a lot of loops of the form:

   while node:
       ... do something with node ...
       node = node.someAttribute

where someAttribute is parentNode or nextSibling or something. These would, 
of course  be better written as for loops with appropriate iterators. e.g.

   for node in node.iterAncestors():
      ... do something with node ...



More information about the Python-list mailing list