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

David Abrahams David Abrahams" <david.abrahams@rcn.com
Fri, 19 Jul 2002 13:16:27 -0400


From: "Guido van Rossum" <guido@python.org>


> > 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".

Do you intend to have a test for "is this an iterator" at all?

> 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.

Makes sense.

> 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.

True.

> 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.

If LBYL is bad, what is introspection good for?

>  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 understand that that's always been "the Python way". However, isn't there
also some implication that some of the special functions are more than just
a way to provide implementations of Python's syntax?  Notes in the docs
like those on __getitem__ tend to argue for that, at least by convention.
Unless I'm misinterpreting things, "the Python way" isn't quite so
one-sided where protocols are concerned.

> 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.

Just for the record, I never meant to imply that it was broken, only that
I'd like to get a little more from it than I currently can.

-Dave