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

Nick Coghlan ncoghlan at gmail.com
Thu Mar 4 14:23:34 CET 2010


spir wrote:
> 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?

Almost all containers should use a separate object for their iterators.
Note that this is already the case for all of Python's standard
container types.

The reason relates to the __reset__ suggestion you describe later in
your message: How do I reset an iterator over a list? Easy, just call
iter() again - it will give me a fresh iterator that starts at the
beginning without affecting the list or my original iterator. By
producing a fresh object for each invocation of __iter__ the state of
the iterators is decoupled from the state of the underlying object which
is generally a good thing from a program design point of view.

(See Eric's suggestion regarding the use of generators as __iter__
methods to easily achieve this behaviour)

Objects with significant state that are also their own iterators are
actually quite rare. File objects certainly qualify (since they base
their iteration off the file object's file pointer), but I can't think
of any others off the top of my head.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list