New submission from Anders Kaseorg <ande...@mit.edu>: 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. ---------- 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 <rep...@bugs.python.org> <http://bugs.python.org/issue8376> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com