[issue8376] Tutorial offers dangerous advice about iterators: “__iter__() can just return self”

Anders Kaseorg report at bugs.python.org
Mon Apr 12 20:44:23 CEST 2010


Anders Kaseorg <andersk at mit.edu> added the comment:

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
"""

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue8376>
_______________________________________


More information about the Python-bugs-list mailing list