我正在编写一个库,希望最终用户能够 Select 性地使用它,就好像它的方法和功能不是协同程序一样.

例如,给定此函数:

@asyncio.coroutine
def blah_getter():
    return (yield from http_client.get('http://blahblahblah'))

最终用户如果不想在自己的代码中使用任何异步功能,仍然需要导入asyncio并运行以下操作:

>>> response = asyncio.get_event_loop().run_until_complete(blah_getter())

如果我能在blah_getter分钟内确定我是否被称为协同程序,并做出相应的react ,那就太酷了.

比如:

@asyncio.coroutine
def blah_getter():
    if magically_determine_if_being_yielded_from():
        return (yield from http_client.get('http://blahblahblah'))
    else:
        el = asyncio.get_event_loop()
        return el.run_until_complete(http_client.get('http://blahblahblah'))

推荐答案

您需要两个函数——异步协同路由和同步正则函数:

@asyncio.coroutine
def async_gettter():
    return (yield from http_client.get('http://example.com'))

def sync_getter()
    return asyncio.get_event_loop().run_until_complete(async_getter())

magically_determine_if_being_yielded_from()实际上是event_loop.is_running(),但我强烈建议不要在同一个函数中混合使用同步和异步代码.

Python-3.x相关问答推荐

在 Python 中比较和排序列之间的值(带有不匹配列)

SQL Server 2022和Python3.10脚本错误

当参数名称与 typing.Protocol 中定义的名称不同时发生 mypy 错误

如何将元组列表拆分为两个单独的列表?

通过点和线计算CV2 Homography

在python中基于列表理解的条件下跳过元素

在两个数据框之间查找相等的列

Python:如何在三个列表中找到共同值

Python 3 变量名中接受哪些 Unicode 符号?

Python 错误:IndexError:字符串索引超出范围

django - 值更改后自动更新日期

如何使用 asyncio 添加连接超时?

ImportError:无法在 PyQt5 中导入名称QStringList

为什么中断比引发异常更快?

变量类型注解NameError不一致

向 Python 函数添加属性的最佳方法

TypeError:多个基地有实例布局冲突

matplotlib - 模块sip没有属性setapi

如何删除目录? os.removedirs 和 os.rmdir 是否只用于删除空目录?

无法解码 Python Web 请求