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

Guido van Rossum guido@python.org
Fri, 19 Jul 2002 12:30:43 -0400


> In Ka-Ping's letter, I did not read that the proposals were orthogonal.
> __iter__ would not be required anymore to identify an iterator as such,
> because __next__ would be sufficient, alone, for this purpose.  That would
> have the effect of cleaning up the iterator protocol from the double
> constraint it currently has, and probably makes things clearer as well.

I think there's been some confusion.  I never intended the test for
"is this an iterator" to be "does it have a next() and an __iter__()
method".  I *do* strongly advise iterators to define __iter__(), but
only because I expect that "for x in iterator:" is useful in  iterator
algebra functions and the like.

In fact, I don't really think that Python currently has foolproof ways
to test for *any* kind of abstract protocol.  Questions like "Is x a
mapping" or "is x a sequence" are equally impossible to answer.

The recommended approach is simply to go ahead and use something; if
it doesn't obey the protocol, it will fail.  Of course, you should
*document* the requirements (e.g., "argument x should be a sequence),
but I've always considered it a case of LBYL syndrome if code wants to
check first.  Note that you can't write code that does something
different for a sequence than for a mapping; for example, the
following class could be either:

  class C:
      def __getitem__(self, i): return i

I realize that this won't make David Abrahams and his Boost users
happy, but that's how Python has approached this issue since its
inception.

I'm fine with suggestions that we should really fix this; I expect
that some way to assert interfaces or protocols will eventually find
its way into the language.

But I *don't* think that the current inability to test for
iterator-ness (or iterable-ness, or multi-iteratable-ness, etc.)
should be used as an argument that there's anything wrong with the
iterator protocol.

(And I've *still* not read Ping's original message...)

--Guido van Rossum (home page: http://www.python.org/~guido/)