while (a=b()) ...

M.-A. Lemburg mal at lemburg.com
Mon May 17 05:25:39 EDT 1999


Tim Peters wrote:
> 
> [Jim Meier]
> > ...
> > Aha! I see now... the * is intended to be the guarauneed-sequential
> > number of the current iteration, then?
> 
> "for x in thing:" follows a protocol that's *defined* to call
> thing.__getitem__ first with 0, then with 1, and so on.  That's how you can
> write a class of your own whose instances participate in "for".  The 0, 1,
> 2, ... sequence is thus not arbitrary, but something the language
> guarantees.
> 
> [...]
>
> Believe Marc-Andre Lemburg has a version of this coded in C, available on
> Starship as part of his tools extension module.  The irony here is that,
> under the covers, map uses the sequence __getitem__ protocol to obtain the
> elements of seq, generating 0, 1, 2, ... on its own, so that it can pair
> your explicit construction of 0, 1, 2, ... with the sequence elements, all
> so you can get at the 0, 1, 2, ... it later constructs *again* all on its
> own in the eventual "for" loop <0.9 wink>.
> 
> Building an artificial and potentially huge list of pairs is unattractive
> for obvious reasons.  The next suggestion is to make it lazy, etc etc.  I
> think that all misses the point:  the index sequence is already part of the
> language definition, and the runtime already generates it.  You simply can't
> *name* it now.

mxTools includes a function called irange(obj) that takes
a sequence and builds a tuple of tuples (index,obj[index])
for the range 0...len(obj). In for-loops this looks like this:

for i,item in irange(obj):
   ...

If you want lazy evaluation, use the xmap() object included
in mxTools (which was donated by Chris Tavares).

mxTools is available via my Python Pages (see below).

BTW, the for-loop implementation can be sped up somewhat by
having the VM use a counter object instead of letting it
generate all the (integer) indices for the __getitem__ protocol.
The irony behind this is that the VM generates the
integer objects only to use the their *value* to
do the actual sequence lookup. The object wrapping is merely
done to be able to push the integer values onto the VM stack.

The counter implementation is included somewhere in...

http://starship.python.net/crew/lemburg/mxPython-1.5.patch.gz

-- 
Marc-Andre Lemburg
______________________________________________________________________
Y2000:                                            Y2000: 228 days left
Business:                                      http://www.lemburg.com/
Python Pages:                 http://starship.python.net/crew/lemburg/






More information about the Python-list mailing list