Why isn't a function declared as async of type types.CoroutineType?

前端 未结 2 1779
你的背包
你的背包 2021-01-21 02:34

Quote from here:

types.CoroutineType

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

Quote f

相关标签:
2条回答
  • 2021-01-21 03:15

    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
    
    0 讨论(0)
  • 2021-01-21 03:24

    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

    0 讨论(0)
提交回复
热议问题