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

Anders Kaseorg report at bugs.python.org
Mon Apr 12 08:35:58 CEST 2010

New submission from Anders Kaseorg <andersk at mit.edu>:

The Python tutorial offers some dangerous advice about adding iterator behavior to a class:
“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.

assignee: georg.brandl
components: Documentation
messages: 102918
nosy: andersk, georg.brandl
severity: normal
status: open
title: Tutorial offers dangerous advice about iterators: “__iter__() can just return self”

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list