Iterator / Iteratable confusion

Michael Spencer mahs at telcopartners.com
Sun Feb 13 18:44:22 EST 2005


> "Francis Girard" <francis.girard at free.fr> wrote in message 
>>an "iterator" doesn't have to support the "__iter__" method
> 
> 
Terry Reedy wrote:
> Yes it does.  iter(iterator) is iterator is part of the iterater protocol 
> for the very reason you noticed...
> 
But, notwithstanding the docs, it is not essential that

iter(iterator) is iterator

  >>> class A(object):
  ...     def __iter__(self):
  ...         return AnIterator()
  ...
  ...
  >>> class AnIterator(object): # an iterator that copies itself
  ...     def next(self):
  ...         return "Something"
  ...     def __iter__(self):
  ...         return AnIterator()
  ...
  >>> a=A()
  >>> i = iter(a)
  ...
  >>> i.next()
'Something'
  >>> j = iter(i)
  >>> j.next()
'Something'
  >>> i is j
False
  >>>

Michael




More information about the Python-list mailing list