Loop-and-a-half (Re: Curious assignment behaviour)
Paul Rubin
phr-n2001d at nightsong.com
Fri Oct 12 01:04:57 EDT 2001
quinn at hork.ugcs.caltech.edu (Quinn Dunkan) writes:
> In programming you define functions to capture your patterns. I'd rather
> write a function than redesign the language. And in this case, the function
> is already written (not that I expected you to know that since it's new).
I think it's a mistake to expose too much abstract machinery in
Python, which is supposed to be a practical language. Like you, I
don't see a need for a lot of "eyebrows" in loops, but I feel Python
suffers by ignoring the tried and true.
Just today I had a bug that went something like:
n = compute_number_of_items()
for i in range(n):
try: process_an_item(items[i])
except: break
update_database('number of items processed = ' % i)
The corresponding C code would have been similar except instead
of "for i in range(n)" it would have said "for (i=0; i<n; i++)".
I tested the Python code on some sample data and it worked fine, so I
checked it in. Then a while later it hit some real data where the
number of items was 0. The C-style for loop would have initialized i
to 0 and then executed the loop zero times, clearly the right thing.
The Python for loop does this cutesy-poo set-theoretic thing instead
(even uselessly allocating a potentially huge block of memory unless
you use xrange instead of range), so that if the range is empty, i
never gets initialized and the update_database call throws an
uninitialized variable exception. Anyway it wasn't a big deal
but I think Python would be improved by having a more traditional
loop construct.
More information about the Python-list
mailing list