[Python-Dev] Re: Single- vs. Multi-pass iterability
Guido van Rossum
guido@python.org
Thu, 18 Jul 2002 16:42:02 -0400
> Maybe the reasons behind having __iter__() returning itself should be
> clearly expressed in the PEP, too. On this list, Tim gave one recently,
> Guido gives another here, but unless I missed it, the PEP gives none.
> Usually, PEPs explain the reasons behind the choices.
Ping added this to the PEP:
The two methods correspond to two distinct protocols:
1. An object can be iterated over with "for" if it implements
__iter__() or __getitem__().
2. An object can function as an iterator if it implements next().
Container-like objects usually support protocol 1. Iterators are
currently required to support both protocols. The semantics of
iteration come only from protocol 2; protocol 1 is present to make
iterators behave like sequences. But the analogy is weak -- unlike
ordinary sequences, iterators are "sequences" that are destroyed
by the act of looking at their elements.
(I could do without the last sentence, since this expresses a value
judgement rather than fact -- not a good thing to have in a PEP's
"specification" section.)
--Guido van Rossum (home page: http://www.python.org/~guido/)