while (a=b()) ...
Hrvoje Niksic
hniksic at srce.hr
Sun May 16 22:06:32 EDT 1999
"Tim Peters" <tim_one at email.msn.com> writes:
> [Tim]
> > "for x in thing:" follows a protocol that's *defined* to call
> > thing.__getitem__ first with 0, then with 1, and so on.
>
> [Hrvoje Niksic]
> > ...and at that, it's a very ugly protocol. If memory serves me
> > right, you're supposed to signal end-of-sequence by explicitly
> > raising IndexError.
>
> Heck of a lot better than leaving the loop as soon as the object
> returns, say, 42.
Is it really? Anyway, the __getitem__ stuff beginning with 0 instead
of using something like __next__ (or whatever) strikes me as ugly just
as much as the exception games. But that is just me.
> > I wonder how expensive it is to trap and raise exceptions in
> > Python (I haven't looked at the interpreter code).
>
> "try" is cheap;
How is it implemented? I assume not with setjmp/longjmp. :-)
> a non-triggered "except" is free; a triggered "except" is relatively
> expensive; sequence iteration triggers an exception once per loop.
In that case, the current protocol should be fine efficiency-wise.
> > Maybe that's why xrange() is slower than range() when common sense
> > says it should be the other way around.
>
> You need to be much clearer about your claim here; certainly
> xrange(1000000) runs much faster than range(1000000) on anyone's
> machine (the former is constant time regardless of argument and the
> latter at best takes time proportional to a million), so your real
> complaint is about something else. If you mean that
>
> for i in xrange(N): pass
>
> is slower than
>
> for i in range(N): pass
Yes, and for reasonably small N's (*less* than 10000), which are the
most frequent. And it's a shame, because range() is one of the few
things I truly dislike in Python. Thinking of:
for i in range(1000):
for j in range(1000):
...
makes me want to cry. *Not* crocodile tears. :-)
> forestalling-the-asterisk-tragedy-ly y'rs - tim
Glad to hear!
More information about the Python-list
mailing list