Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is Python's coroutine type defined?

I'm working on Python 3.5.1 and I want to be able to tell if a function has returned as coroutine object but I cannot find where the coroutine type is defined, instead as of late I've been using the below snippet to get the type through instantiating a coroutine with a function.

async def _f():
    pass
COROUTINE_TYPE = type(_f())

There's got to be a better way to do this, my question is where is this type defined so I can use it directly?

like image 287
sethmlarson Avatar asked Dec 18 '22 15:12

sethmlarson


2 Answers

Probably the best way to access the coroutine type is through the types module:

import types

types.CoroutineType  # here it is

That's not actually where the coroutine type is defined - types.py does pretty much the same thing you're doing to get at it - but it's the standard Python-level way to access the type.

If you want to see the actual definition of the type, that's in Include/genobject.h and Objects/genobject.c. Look for the parts that say PyCoroWhatever or coro_whatever.

like image 188
user2357112 supports Monica Avatar answered Dec 21 '22 09:12

user2357112 supports Monica


The best way to tell if a function is a coroutine is with asyncio.iscoroutinefunction.

asyncio.iscoroutinefunction(some_func)
like image 24
dirn Avatar answered Dec 21 '22 09:12

dirn