繁体   English   中英

知道function里面是同步调用还是异步调用

[英]Know within function if it was called synchronously or asynchronously

我想知道是否有人知道任何神奇的 function 可能会告诉我运行的 function 是否已被同步或异步调用。 长话短说,我想做以下事情:

def fsync():
    was_called_async() # >>> False

async fasync():
    was_called_async() # >>> True

fsync()
await fasync()

这听起来可能有点奇怪,我同意,这是理所当然的。 原因是因为我正在尝试实现类似于functools.singledispatchmethod但用于同步和异步方法的 function 。 这需要使用装饰器,因此需要“等待内省”。 我目前的工作方法在这里按预期工作:

from toolbox.cofunc import cofunc
import asyncio
import time

@cofunc
def hello():
    time.sleep(0.01)
    return "hello sync world!"

@hello.register
async def _():
    await asyncio.sleep(0.01)
    return "hello async world!"

async def main():
    print(hello())        # >>> "hello sync world!"
    print(await hello())  # >>> "hello async world!"

asyncio.run(main())

但是,它使用了inspect模块,而不是我想要依赖的东西(获取前一帧并搜索await )。 如果有人知道那将是可爱的替代方案。

只是没有一个好方法来做你正在寻找的东西。

function 被“同步调用”或“异步调用”之间没有实际区别。 无论哪种方式,function 都会被调用。

最接近差异的是调用者对返回值所做的事情,但即使寻找await也是一个坏主意,因为像

await asyncio.gather(yourfunc(), something_else())

或者

asyncio.run(yourfunc())

直觉上会被认为是“异步的”。

到目前为止,最可靠的选择是只有两个功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM