Home > Software engineering >  generator is instance of iterator and it is not
generator is instance of iterator and it is not

Time:03-03

I have the following code. In the first validation I get False but True in second validation. Can someone help me understand how the 2 conditions are different? I am using Python-3.9.5 on Windows-10

from collections.abc import Iterator

i1 = iter([])
g1 = (lambda : (yield))()
print (isinstance(g1, type(i1)))

print(isinstance(g1, Iterator))

CodePudding user response:

If you print(type(i1)) you will see that it is not Iterator but list_iterator. That is a specific implementation of an iterator, whereas Iterator is the abstract base type of iterators.

Generator and list_iterator are both subtypes of the base class Iterator.

>>> from collections.abc import Iterator
>>> type1 = type(iter([]))
>>> type1
<class 'list_iterator'>
>>> issubclass(type1, Iterator)
True
>>> def gen():
...   yield 1
...
>>> type2 = type(gen())
>>> type2
<class 'generator'>
>>> issubclass(type2, Iterator)
True
>>> type1 is type2
False
  • Related