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

Brett Cannon brett at python.org
Thu Mar 4 21:25:19 CET 2010


On Thu, Mar 4, 2010 at 05:23, Nick Coghlan <ncoghlan at gmail.com> wrote:

> 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.
>

There is also the issue of backwards-compatibility when iterators were
introduced. Just because someone decided to have a method named next() when
iterators were introduced does not mean they intended for it to be viewed as
a sequence. Requiring an iterable to define __iter__() took care of the
ambiguity.

-Brett




>
> 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
> ---------------------------------------------------------------
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20100304/09a9012c/attachment.html>


More information about the Python-ideas mailing list