Iterator / Iteratable confusion
Michael Spencer
mahs at telcopartners.com
Tue Feb 15 14:12:25 EST 2005
Michael Spencer wrote:
>But, notwithstanding the docs, it is not essential that
>iter(iterator) is iterator
Terry Reedy wrote:
> iter(iterator) is iterator is part of the iterater protocol
>
> [...]I interpret [your post] as saying three things:
>
> 1. "There is more than one possible definition of 'iterator'."
Terry, thanks for responding in depth.
> 2. "It is not essential to not do something wasteful as long as it is
> otherwise inconsequential."
Not that "iter(iterator) is iterator" is somehow wasteful (actually it seems
conservative), but rather that alternative behavior is readily implmented. You
point out, reasonably, that if I do that, then what I get is not then an
iterator, because it fails to conform with the protocol.
However, I suggest that there may be cases where "iter(iterator) is not
iterator" is useful behavior. What to call such an object is another matter.
For example, consider:
import itertools as it
def tee2(iterable):
class itertee(object):
def __init__(self, iterator):
self.iterator = iterator
def __iter__(self):
return itertee(self.iterator.__copy__())
def next(self):
return self.iterator.next()
return itertee(it.tee(iterable, 1)[0])
This returns an itertee instance which simply wraps the tee iterator returned by
itertools. However iter(itertee instance) returns a copy of its iterator. So
this object creates as many independent iterators over iterable as are required.
In an earlier post in this thread, I included several examples of generating
infinite series using iterator-copying like this. I implemented the copying as
a method of a containing iterable 'Stream', rather than of the iterators
themselves, partly to respect the 'iterator protocol'.
> 3. "You can substitute a copy of an object that is never mutated for the
> object itself."
>
This was not my intended point, although I accept that my example was too abstract.
Cheers
Michael
More information about the Python-list
mailing list