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.