[Python-Dev] Single- vs. Multi-pass iterability

Andrew Koenig ark@research.att.com
Fri, 12 Jul 2002 09:32:36 -0400 (EDT)


Oren> 1. There is no iterable object. An iterator object was created
Oren> directly.  For example, the result of a generator function is an
Oren> iterator which isn't the result of some container's __iter__
Oren> method.

Yes.

Oren> 2. The iterator was received as an argument and the caller sent
Oren> iter(x) instead of x.  In that case I guess it means that the
Oren> caller doesn't *want* to give me access to x.

3. The caller sent an iterator that refers to an element of the
container other than the initial one.  For example:

	  def findafter(it, x):
	      it = iter(it)
	      while it.next() != x:
		    pass
	      return it

This function locates the first element equal to x in the sequence
denoted by iter, and returns an iterator that refers to the element
after the one equal to x.  It raises StopIteration if no such element
exists.

Now, suppose you want to use this function to find all of the elements
in a sequence that are equal to x.  On the second and subsequent calls,
you're going to have to pass an iterator as the first argument, because
passing the container isn't going to give you the right answer.

For another, more detailed example of how sensitive library design
is to the details of iterator behavior, please look at
http://www.research.att.com/~ark/design.pdf
(I hope I have uttered the right incantations to make it available
outside our firewall; if I haven't, please let me know)