简体   繁体   English

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

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

I was wondering if someone knew of any magic function that could potentially tell me if the function running has been called synchronously or asynchronously.我想知道是否有人知道任何神奇的 function 可能会告诉我运行的 function 是否已被同步或异步调用。 Long story short, I would like to do the following:长话短说,我想做以下事情:

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

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

fsync()
await fasync()

This might sound a bit weird, and granted, I agree.这听起来可能有点奇怪,我同意,这是理所当然的。 The reason why is because I'm trying to implement a function similar to functools.singledispatchmethod but for sync and async methods.原因是因为我正在尝试实现类似于functools.singledispatchmethod但用于同步和异步方法的 function 。 This requires a decorator to be utilized, and therefore the need for "await-introspection."这需要使用装饰器,因此需要“等待内省”。 My current working method here works as expected:我目前的工作方法在这里按预期工作:

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

However, it utilizes the inspect module, and is not something I would want to be dependent on (gets the previous frame and searches for await ).但是,它使用了inspect模块,而不是我想要依赖的东西(获取前一帧并搜索await )。 If anyone knows of an alternative that would be lovely.如果有人知道那将是可爱的替代方案。

There just isn't a good way to do what you're looking for.只是没有一个好方法来做你正在寻找的东西。

There's no actual difference between a function being "called synchronously" or being "called asynchronously". function 被“同步调用”或“异步调用”之间没有实际区别。 Either way, the function is just called.无论哪种方式,function 都会被调用。

The closest thing to a difference is what the caller does with the return value, but even looking for await is a bad idea, because things like最接近差异的是调用者对返回值所做的事情,但即使寻找await也是一个坏主意,因为像

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

or或者

asyncio.run(yourfunc())

would intuitively be considered "async".直觉上会被认为是“异步的”。

The most reliable option by far is to just have two functions.到目前为止,最可靠的选择是只有两个功能。

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

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