[Python-ideas] iterable: next() and __iter__() -- and __reset()
Éric Araujo
merwok at netwok.org
Thu Mar 4 13:37:56 CET 2010
Hello list
Some complementary information to Chris Rebert’s message.
> (1) I do not understand an iterable type's __iter__() method to be
> compulsary. [...]
The iterable and the iterator protocols are two different things. Every
iterator is iterable, but not every iterable object is an iterator (see
<http://docs.python.org/library/collections>). There are situations
where it makes sense to use a different class as iterator (can’t find
examples right now, hope other people will chime in), and a lot of
situations where it’s fine to implement both protocols on the same class.
> Actually, each time I have defined one, I had to write:
> def __iter__(self):
> return self
Instead of returning self in __iter__ and then defining a function in
next, i.e. returning values and raising StopIteration, you can define
__iter__ as a generator (i.e. yield values instead of returning them)
and not need to write next. Helpful documentation here:
<http://docs.python.org/reference/datamodel#object.__iter__> and
<http://docs.python.org/library/stdtypes#typeiter>
> (3) What I miss actually for iterables (which are their own iterator)
> is a kind of __reset__(). In some cases, it is only needed to allow a
> new iteration from start.[...]
Didn’t really understand your use case here, but perhaps the extension
of the yield statement done in version 2.5 can help you here:
<http://docs.python.org/reference/expressions#yieldexpr>
<http://www.python.org/dev/peps/pep-0342/>
Hope this helps.
Regards
More information about the Python-ideas
mailing list