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

Ray.Allen report at bugs.python.org
Mon Apr 12 17:09:28 CEST 2010


Ray.Allen <ysj.ray at gmail.com> added the comment:

I think there is not much ploblem. Please notice this sentence in the previous paragraph in the toturial :

"Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time."

I think it's clear enough that the container object is different from the iterator object, what exactly has the iterator behavior is the iterator object, not the container object. And this sentence you mentioned:

"If the class defines next(), then __iter__() can just return self:"

is to teach you define a iterator, not a container. So by reading it carefully, you won't define something that is both a container and a iterator, will you? 

If you really define a next() on a class which you want it be a container, and then define a __iter__() on it and return self, then your container is exactly a generator, not a container. And a generator can certainly iterate only once.

----------

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


More information about the Python-bugs-list mailing list