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

R. David Murray report at bugs.python.org
Mon Apr 12 19:24:05 CEST 2010

R. David Murray <rdmurray at bitdance.com> added the comment:

It might be worth mentioning in the tutorial the specific problem the OP points out: that if an object returns itself in __iter__, then that object can have only one iteration state.  And that therefor only an object that is itself a unique iterator (as opposed to a collection wanting to allow iteration) should return itself as __iter__.

Also note that in the example in the tutorial it says "easy to add the behavior", which *in context* is wrong; pedagogically the better thing to do would be to say "it is easy to write a class that implements an iterator".  As Éric said, splitting the text so that returning an iterator from a collection and constructing an iterator class are distinct topics would greatly improve the exposition.

I'm an experienced Python coder, and I've made this mistake myself.  Often it doesn't break because the code only iterates the object once, but it would be better to have the tutorial encourage doing this correctly by providing good examples and explanations.

nosy: +r.david.murray
priority:  -> normal
type:  -> behavior
versions: +Python 2.6, Python 2.7, Python 3.1, Python 3.2

Python tracker <report at bugs.python.org>

More information about the Python-bugs-list mailing list