Iterators, iterables and special objects

Random832 random832 at fastmail.com
Fri Jul 24 14:44:06 EDT 2020


On Thu, Jul 23, 2020, at 05:14, Peter Slížik wrote:
> > Works in what way? You can't use it in a 'for' loop if it doesn't
> > define __iter__.
> >
> 
> class Iterable:
>     def __iter__(self):
>         return Iterator(...)
> 
> class Iterator:
>     def __next__(self):
>         return <next item>
> 
>     # No __iter__ here.
>     # I've just forgotten to def it.
> 
> With this setup, using for to iterate over Iterable *will* still work,
> though you cannot use the trick described below.

Sure, but you can't use for to iterate over _Iterator itself_, or do anything else useful with it.

>>> class Iterator:
...   def __init__(self): self.done=False
...   def __next__(self):
...    if self.done: raise StopIteration
...    self.done = True
...    return 1
... 
>>> [*Iterator()]
>>> [*map(lambda x:x, Iterator())]
>>> [*filter(lambda x:True, Iterator())]
>>> for x in Iterator(): pass
...
>>> [x for x in Iterator()]
[all of the above have the exact same exception]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'Iterator' object is not iterable
>>> def gen():
...  yield from Iterator()
...
>>> [*gen()]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in gen
TypeError: 'Iterator' object is not iterable


More information about the Python-list mailing list