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, georg.brandl
Date 2010-04-12.06:35:55
SpamBayes Score 1.5367743e-07
Marked as misclassified No
Message-id <1271054158.9.0.672918640444.issue8376@psf.upfronthosting.co.za>
In-reply-to
Content
The Python tutorial offers some dangerous advice about adding iterator behavior to a class:
http://docs.python.org/tutorial/classes.html#iterators
“By now you have probably noticed that most container objects can be looped over using a for statement:
…
Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define a __iter__() method which returns an object with a next() method. If the class defines next(), then __iter__() can just return self:”

This is reasonable advice for writing an iterator class, but terrible advice for writing a container class, because it encourages you to associate a single iterator with the container, which breaks nested iteration and leads to hard-to-find bugs.  (One of those bugs recently made its way into the code handout for a problem set in MIT’s introductory CS course, 6.00.)

A container class’s __iter__() should return a generator or an instance of a separate iterator class, not self.  The tutorial should make this clearer.
History
Date User Action Args
2010-04-12 06:35:58andersksetrecipients: + andersk, georg.brandl
2010-04-12 06:35:58andersksetmessageid: <1271054158.9.0.672918640444.issue8376@psf.upfronthosting.co.za>
2010-04-12 06:35:57andersklinkissue8376 messages
2010-04-12 06:35:55anderskcreate