3

Quote from here:

types.CoroutineType

The type of coroutine objects, created by async def functions.

Quote from here:

Functions defined with async def syntax are always coroutine functions, even if they do not contain await or async keywords.

Python console session:

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import types
>>> def f(): pass
...
>>> async def g(): pass
...
>>> isinstance(f, types.FunctionType)
True
>>> isinstance(g, types.FunctionType)
True
>>> isinstance(g, types.CoroutineType)
False
>>>

Why doesn't isinstance(g, types.CoroutineType) evaluate to True?

2 Answers 2

5

There's a difference between coroutine and coroutine function. The same way as there is a difference between generator and generator function:

Calling the function g returns a coroutine, e.g.:

>>> isinstance(g(), types.CoroutineType)
True

If you need to tell if g is a coroutine function (i.e. would return a coroutine) you can check with:

>>> from asyncio import iscoroutinefunction
>>> iscoroutinefunction(g)
True
1
  • Ooh, I'm a little late Jan 17, 2016 at 16:51
1

g by itself is not a valid Coroutine function when used that way:

isinstance(g, types.CoroutineType)

This is similar to the difference between a generator and a generator function. Instead, use g() to compare:

isinstance(g(), types.CoroutineType)

You could also try iscoroutinefunction(g) instead, much more shorter and neater:

from asyncio import iscoroutinefunction
iscoroutinefunction(g)   #Return true

Read more here: https://docs.python.org/3/library/asyncio-task.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.