This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author andersk
Recipients andersk, eric.araujo, georg.brandl, r.david.murray, rhettinger, ysj.ray
Date 2010-04-12.18:44:20
SpamBayes Score 5.228383e-09
Marked as misclassified No
Message-id <1271097863.27.0.306228199253.issue8376@psf.upfronthosting.co.za>
In-reply-to
Content
As an experienced Python programmer I am obviously aware that the tutorial is trying to teach how to make an iterator class, not how to make a container class.

But the tutorial doesn’t make that *clear*.  It should be much more explicit about what it is explaining to avoid confusing those concepts in the minds of beginners.  (Or even the staff of the MIT introductory CS course.)

One way to fix this confusion would be to explain what one should do for both container classes and iterator classes:

"""
Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your container classes.  Define a :meth:`__iter__` method which returns an object of a separate iterator class.  The iterator class should have a :meth:`next` method and an :meth:`__iter__` method (the :meth:`__iter__` method of the iterator class should just return ``self``)::

   class ReverseList(object):
       "Container that lets you iterate over the items backwards"
       def __init__(self, data):
           self.data = data
       def __iter__(self):
           return ReverseIterator(self.data)

   class ReverseIterator(object):
       "Iterator for looping over a sequence backwards"
       def __init__(self, data):
           self.data = data
           self.index = len(data)
       def __iter__(self):
           return self
       def next(self):
           if self.index == 0:
               raise StopIteration
           self.index = self.index - 1
           return self.data[self.index]

   >>> for char in ReverseIterator('spam'):
   ...     print char
   ...
   m
   a
   p
   s
   >>> for char in ReverseList([1,2,3]):
   ...     print char
   ...
   3
   2
   1
"""
History
Date User Action Args
2010-04-12 18:44:24andersksetrecipients: + andersk, georg.brandl, rhettinger, eric.araujo, r.david.murray, ysj.ray
2010-04-12 18:44:23andersksetmessageid: <1271097863.27.0.306228199253.issue8376@psf.upfronthosting.co.za>
2010-04-12 18:44:21andersklinkissue8376 messages
2010-04-12 18:44:21anderskcreate