【问题标题】:Why isn't a function declared as async of type types.CoroutineType?为什么不将函数声明为 types.CoroutineType 类型的异步函数?
【发布时间】:2016-01-17 16:39:22
【问题描述】:

引用here:

types.CoroutineType

协程对象的类型,由 async def 函数创建。

引用here:

使用 async def 语法定义的函数始终是协程函数,即使它们不包含 await 或 async 关键字。

Python 控制台会话:

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
>>>

为什么isinstance(g, types.CoroutineType) 不计算为True

【问题讨论】:

    标签: python python-3.x async-await


    【解决方案1】:

    协程和协程函数是有区别的。同理,生成器和生成器函数也有区别:

    调用函数g返回一个协程,例如:

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

    如果您需要判断 g 是否是协程函数(即会返回协程),您可以检查:

    >>> from asyncio import iscoroutinefunction
    >>> iscoroutinefunction(g)
    True
    

    【讨论】:

    • 哦,我来晚了
    【解决方案2】:

    g 以这种方式使用时,它本身不是一个有效的协程函数:

    isinstance(g, types.CoroutineType)
    

    这类似于生成器和生成器函数之间的区别。而是使用g() 进行比较:

    isinstance(g(), types.CoroutineType)
    

    你也可以试试iscoroutinefunction(g),更短更整洁:

    from asyncio import iscoroutinefunction
    iscoroutinefunction(g)   #Return true
    

    在此处阅读更多信息:https://docs.python.org/3/library/asyncio-task.html

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 2018-06-03
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2019-10-24
      • 2011-06-23
      • 2019-02-26
      • 2015-06-27
      相关资源
      最近更新 更多