This problem is probably not complicated, but I'm new to async library and I just can't figure this out.
Let's say I have a synchronous function from which I want to call an async function without transforming the synchronous function into an asynchronous one. The synchronous function needs to wait for the async function to complete and return the value it provides. It's fine if it blocks execution in the meantime. All of this is necessary because the async function comes from a library.
How can I retrieve the result computed by the async function?
- There is already a running event loop, and I have a reference to it.
- They are running on the same thread, so I don't need another thread.
- I can't use run_until_complete() because it somehow conflicts with the already running event loop.
import asyncio
class Sample:
def __init__(self):
self.state = self.compute_sync() # I want to call async from this constructor
async def io_function(self):
print("started")
x = await asyncio.sleep(1) # using an async library here
print("ended")
return x.result()
def compute_sync(self):
io_result = self.io_function() # I want the result of this without using await
return 'local_data' + io_result
async def main():
await asyncio.sleep(1) # other IO stuff
s = Sample()
print(s)
asyncio.run(main())
(The code above is extremely simplified, maybe it does not reflect the real use case, but the comments will maybe help what I need to do here)
- I'm looking for answers with the newest version of Python (which currently is 3.13).
- I don't want to use an external async library if possible.