Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asyncio.iscoroutinefunction returns False for asynchronous generator

The following asynchronous generator code is taked straight out of PEP525:

async def gen():
    await asyncio.sleep(0.1)
    v = yield 42
    print(v)
    await asyncio.sleep(0.2)

However when I call (with python3.6):

print(asyncio.iscoroutinefunction(gen), asyncio.iscoroutine(gen))

I get:

False, False

Why does asynchronous generator fails to identify as a coroutine function?

Is there another way to identify it as a coroutine function?

like image 378
Periodic Maintenance Avatar asked Jun 26 '26 01:06

Periodic Maintenance


1 Answers

You want to use inspect.isasyncgenfunction() (and inspect.isasyncgen() for the result of calling gen()):

>>> import inspect
>>> print(inspect.isasyncgenfunction(gen), inspect.isasyncgen(gen()))
True True

There is no type hierarchy relationship between async functions and async generator functions.

Also, the only reason the asyncio.iscoroutine*() functions exist at all is to support the legacy generator-based @asyncio.coroutine decorator, which can't be used to create async generators. If you don't need to support older codebases that might still use those (so predating Python 3.5) I'd just stick with the inspect.is*() functions.

like image 184
Martijn Pieters Avatar answered Jun 28 '26 14:06

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!