[Python-ideas] iterable: next() and __iter__() -- and __reset()

Antoine Pitrou solipsis at pitrou.net
Fri Mar 5 00:54:05 CET 2010

Le Thu, 4 Mar 2010 11:35:53 +0100,
spir <denis.spir at gmail.com> a écrit :
> (1) I do not understand an iterable type's __iter__() method to be
> compulsary. Actually, each time I have defined one, I had to write:
> def __iter__(self): return self
> So, I guess that if python does not find __iter__(), but the object
> defines next(), then by default the said object could be used as its
> own iterator.

Explicit is better than implicit, though.
In many non-trivial cases, the iterator will have to be a separate
object anyway.
Also, please note you can implement __iter__ as a generator, which
makes things very easy for the simple cases:

>>> class C(object):
...   def __iter__(self):
...     yield 1
...     yield 2
>>> c = C()
>>> it = iter(c)
>>> it
<generator object __iter__ at 0xb746c0f4>
>>> next(it)
>>> next(it)
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
>>> list(c)
[1, 2]

> (3) What I miss actually for iterables (which are their own iterator)
> is a kind of __reset__().

No, really, you don't want this, unless you like PHP. As others said,
calling iter() again is the well-defined generic way to "reset" your
Then, particular cases can warrant specific APIs, such as file.seek().



More information about the Python-ideas mailing list