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

Georg Brandl g.brandl at gmx.net
Thu Mar 4 22:43:53 CET 2010


Am 04.03.2010 11:35, schrieb spir:
> Hello,
> 
> (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. This is what I understand by "iterable"
> and next() is the required method for it. Or even better: only if the object
> does not define next(), then python falls back to looking for __iter__(). Is
> there any obstacle for this I cannot see? Side-question: In which cases is it
> necessary to define the iterator as a separate object?

I would say that in most cases it makes sense to have the iterator be a separate
object.  However, when writing an __iter__() in Python, you almost always can
make it a generator, which already does this for you -- each call to __iter__()
will return a new generator.

> (2) But: for any reason next() is not spelled as a "magic" method. If this
> method becomes the distinctive method of iterables, then it should be called
> __next__() for consistency. Side-question: Why is it called next(), as it is
> a magic method for iterators already?

Because it is supposed to be called directly.  __iter__() isn't.  (This changes
with Python 3, where you have next() as a builtin.)  As such, this is the same
question as "why is it called readline(), not __readline__()."  readline(), just
like next(), is a method defined by a protocol (file vs iterator).

Georg




More information about the Python-ideas mailing list