PEP-0234: Iterators

Neelakantan Krishnaswami neelk at alum.mit.edu
Fri Feb 16 10:49:28 EST 2001


I have a couple of comments about the iterators proposal. The need for
improving the iteration protocol has been apparent for a really long
time, and I'm really glad to see that a PEP for it has appeared.
However, in its current form I think that what the PEP proposes can be
simplified a bit.

You can get a simplification if the separate protocols for sequence
and mappings were combined, and an iterator was an object with methods
"current_index", "current_value", and "next_state". The "current
index" of a sequence would be the position in the list, and the
"current index" of a mapping would the key that yields that value.

So then a loop like:

for elt in coll:
   # Stuff

would be equivalent to:

iterator = coll.__iter__()
while 1:
    elt = iterator.current_value()

    # Stuff

    try:
        iterator = iterator.next_state()
    except IndexError:
        break

The "key:value" syntax could then be the same for mappings and
sequences:

for key:value in coll:
    # Stuff

iterator = coll.__iter__()
while 1:
    key = iterator.current_index()
    val = iterator.current_value()

    # Stuff

    try: 
	iterator = iterator.next_state()
    except IndexError:
	break

And similar variations (":value", "key:") would follow logically.


Neel



More information about the Python-list mailing list