Adjusted the wording to make __iter__() more strongly required on iterators.

See http://mail.python.org/pipermail/python-dev/2002-July/026668.html .

Added text describing the distinct purposes of __iter__() and next().
See http://mail.python.org/pipermail/python-dev/2002-July/026683.html .
This commit is contained in:
Ka-Ping Yee 2002-07-18 20:00:21 +00:00
parent ed5074fb4e
commit 6c29d4df54
1 changed files with 20 additions and 4 deletions

View File

@ -139,10 +139,26 @@ Python API Specification
Classes can define how they are iterated over by defining an
__iter__() method; this should take no additional arguments and
return a valid iterator object. A class is a valid iterator
object when it defines a next() method that behaves as described
above. A class that wants to be an iterator also ought to
implement __iter__() returning itself.
return a valid iterator object. A class that wants to be an
iterator should implement two methods: a next() method that behaves
as described above, and an __iter__() method that returns self.
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.
Consequently, whenever any Python programmer says "for x in y",
he or she must be sure of whether this is going to destroy y.
Dictionary Iterators