From 6c29d4df54d5157b6e9bad84156fd51dc3f7b5b4 Mon Sep 17 00:00:00 2001 From: Ka-Ping Yee Date: Thu, 18 Jul 2002 20:00:21 +0000 Subject: [PATCH] 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 . --- pep-0234.txt | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/pep-0234.txt b/pep-0234.txt index 8445de7ad..f406bd616 100644 --- a/pep-0234.txt +++ b/pep-0234.txt @@ -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