我正在编写一个库,我希望最终用户能够有选择地使用它,就好像它的方法和函数不是协程一样。
例如,给定这个函数:
@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 - 如何编写可选择充当常规函数的 asyncio 协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30155138/