Imagine I have a set of functions like this:
def func1():
func2()
def func2():
time.sleep(1) # simulate I/O operation
print('done')
I want these to be usable synchronously:
# this would take two seconds to complete
func1()
func1()
as well as asynchronously, for example like this:
# this would take 1 second to complete
future = asyncio.gather(func1.run_async(), func1.run_async())
loop = asyncio.get_event_loop()
loop.run_until_complete(future)
The problem is, of course, that func1
somehow has to propagate the "context" it's running in (synchronously vs. asynchronously) to func2
.
I want to avoid writing an asynchronous variant of each of my functions because that would result in a lot of duplicate code:
def func1():
func2()
def func2():
time.sleep(1) # simulate I/O operation
print('done')
# duplicate code below...
async def func1_async():
await func2_async()
async def func2_async():
await asyncio.sleep(1) # simulate I/O operation
print('done')
Is there any way to do this without having to implement an asynchronous copy of all my functions?