[Python-ideas] generator vs iterator etc. (was: How assignment should work with generators?)

Steven D'Aprano steve at pearwood.info
Tue Nov 28 20:48:19 EST 2017


On Tue, Nov 28, 2017 at 04:25:23PM +0000, Rob Cliffe wrote:

> Given that we have this kind of arcane discussion fairly regularly (not 
> just in this thread), and it always makes my head spin, and it seems I'm 
> not the only one who gets confused:
> 
> How about having a module that provides functions such as
> 
>     isgenerator  isiterator  isiterable  etc.

There is no single module that does this, but the inspect module comes 
close:

inspect.isgenerator
inspect.isgeneratorfunction

will tell you the difference between these two:

def gen_function():
    yield 1

generator = gen_function()


The collections.abc module has ABCs that you can use with isinstance:

collections.abc.Iterable
collections.abc.Iterator
collections.abc.Sequence


For example, we know that range is not a generator but is a sequence:

py> inspect.isgenerator(range(10))
False
py> isinstance(range(10), collections.abc.Sequence)
True



-- 
Steve


More information about the Python-ideas mailing list