a pyrex-inspired for-i-from-1-to-n construct backported to Python. Good idea? Bad Idea? PEP?

WP warrenpstma at _______.com.hotmail
Wed Apr 2 09:14:24 EST 2003


Greg Ewing wrote the following Pyrex snippet:
>     for i from 0 <= i < n:
>       result.append(a[i])

This pyrex snippet reminds me (because of its orthogonality to C) of one 
thing, more than tab indents, that I have always thought was bogus in Python, 
which is the handling of integer loops.  range(0,n) sucks, xrange(0,n) is an 
interesting hack which obscures the readability of code, and post 2.x versions 
of python, with generators, and other 'inverted' ways of accomplishing the 
obvious procedural effect of an integer for loop, are all just ways of 
obfuscating otherwise perfectly readable python code. Okay, so I'm being
opinionated. I know that. But does anyone else thing that for the extremely 
common (and therefore bytecode optimizeable, syntax customizeable) case where 
you need to do a for loop over a range (possibly large range) of integers, 
that a language level keyword construct (such as the above) would be 
preferable to Python's choices of range, xrange, generators, custom 
class-based iterators, and whatever else you can come up with, that the lack 
of the most common idiom, being expressed in a bytecode optimized fashion 
would be good?

Of course, it all comes I suppose from integers being "first class objects" 
and thus, not actually integers, they are actually immutable objects which 
contain an integer, and so we get to the ugly condition where "i++" actually 
decref's one object, and either looks up or creates another object, and 
increfs it.  Hardly a fast operation to implement, but certainly one of the 
most common idioms in all of programming.

Going back (dizzyingly) from the bytecode/c implementation, to the syntax, for 
a moment. Imagine if Python had a pyrex-like first-class iteration case, where 
i (in the above example) is not an integer, but rather a reference to the 
for-integer-bytecode emitted by the compiler, an object which knows (in C) how 
to increment i's value quickly, and jump out of a loop when the limit n is 
reached.

Ever since Python 1.5.2, I have been hacking around on my own to see if I 
could get huge speed improvements out of Python.  I have settled down to the 
reality that Python+Pyrex, with syntactical speedbumps in between them, are 
probably the way things are going to stay. But I can dream, can't I?

Just a thought, no intent to start another PEP-flamewar.  ;-)

Warren





More information about the Python-list mailing list