简体   繁体   中英

How can you determine if a function return value is a generator?

the yield return a collections.Iterable but many types are also iterable

def aaaa():
    yield 1
    yield 2
    yield 3 

d = aaaa()

print(d,type(d),isinstance(d, collections.Iterable))

the print type

<generator object aaaa at 0x0000000002626B88> <class 'generator'> True

i didn't find the class 'generator' or i can't do typecheck.

If you want to check if the iterable is a generator object:

import types
isinstance(aaaa(), types.GeneratorType) # ==> True

If you want to check if the function contains yield statements (ie the function is a generator):

import inspect
inspect.isgeneratorfunction(aaaa) # ==> True

Have a look at the inspect module, and in particular inspect.isgeneratorfunction .

That said, the more interesting question is whether it's a list or other iterable. To answer that question, you can just check if __getitem__ is defined on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM