Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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). If anyone knows of an alternative that would be lovely.

like image 336
Felipe Avatar asked Oct 27 '25 08:10

Felipe


1 Answers

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". Either way, the function is just called.

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

like image 158
user2357112 supports Monica Avatar answered Oct 29 '25 23:10

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!