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

Ka-Ping Yee ping@zesty.ca
Mon, 15 Jul 2002 16:16:56 -0700 (PDT)


On Tue, 9 Jul 2002, Tim Peters wrote:
> > The context does not make it clear that the iterator's __iter__ method is
> > *only* required whenever one *also* wants to use an iterator as an
> > iterable.
>
> That's not how the iteration protocol is defined, and isn't how it should be
> defined either.  Requiring *some* method with a reserved name is an aid to
> introspection

This is a terrible reason for the existence of an __iter__ method, because
(a) it's a bad way to do type-checking and (b) it doesn't even work.

(a) If we followed this logic, we'd insist on having a useless __dict__
method on dictionaries, a useless __list__ method on lists, etc. etc.
just so we could check types by looking for these methods.

As i understood it, the Python way is to let the protocol speak for itself.
Something that wants to give out keys can implement the keys() method,
something that wants to act like a container can implement __getitem__,
and so on.  There's no need to make an additional declaration of dict-ness
by adding a dummy __dict__ method -- indeed, sometimes we don't *want* to
make that kind of commitment, and Python allows that flexibility.

It seems to me that dictionaries are to keys() as iterators are to next().

(b) Looking for __iter__ is not a valid test for iterator-ness.  Files
and other iterable objects supply __iter__, but they are not iterators.
So it doesn't work as a type test.

I agree with Oren that it makes more sense for iterator-fetching to be
a convenience handled by the implementations of "for" and "in", rather
than foisting the extra hassle of "def __iter__(self): return self" on
every individual iterator implementation.


-- ?!ng