Reputation: 251
I'm trying to wrap an async function up so that I can use it without importing asyncio in certain files. The ultimate goal is to use asynchronous functions but being able to call them normally and get back the result.
How can I access the result from the callback function printing(task)
and use it as the return of my make_task(x)
function?
MWE:
#!/usr/bin/env python3.7
import asyncio
loop = asyncio.get_event_loop()
def make_task(x): # Can be used without asyncio
task = loop.create_task(my_async(x))
task.add_done_callback(printing)
# return to get the
def printing(task):
print('sleep done: %s' % task.done())
print('results: %s' % task.result())
return task.result() # How can i access this return?
async def my_async(x): # Handeling the actual async running
print('Starting my async')
res = await my_sleep(x)
return res # The value I want to ultimately use in the real callback
async def my_sleep(x):
print('starting sleep for %d' % x)
await asyncio.sleep(x)
return x**2
async def my_coro(*coro):
return await asyncio.gather(*coro)
val1 = make_task(4)
val2 = make_task(5)
loop.run_until_complete(my_coro(asyncio.sleep(6)))
print(val1)
print(val2)
Upvotes: 0
Views: 2168
Reputation: 39526
If I understand correctly you want to use asynchronous functions but don't want to write async
/await
in top-level code.
If that's the case, I'm afraid it's not possible to achieve with asyncio
. asyncio
wants you to write async
/await
everywhere asynchronous stuff happens and this is intentional: forcing to explicitly mark places of possible context switch is a asyncio
's way to fight concurrency-related problems (which is very hard to fight otherwise). Read this answer for more info.
If you still want to have asynchronous stuff and use it "as usual code" take a look at alternative solutions like gevent.
Upvotes: 1
Reputation: 154866
Instead of using a callback, you can make printing
a coroutine and await
the original coroutine, such as my_async
. make_task
can then create a task out of printing(my_async(...))
, which will make the return value of printing
available as the task result. In other words, to return a value out of printing
, just - return it.
For example, if you define make_task
and printing
like this and leave the rest of the program unchanged:
def make_task(x):
task = loop.create_task(printing(my_async(x)))
return task
async def printing(coro):
coro_result = await coro
print('sleep done')
print('results: %s' % coro_result)
return coro_result
The resulting output is:
Starting my async
starting sleep for 4
Starting my async
starting sleep for 5
sleep done
results: 16
sleep done
results: 25
<Task finished coro=<printing() done, defined at result1.py:11> result=16>
<Task finished coro=<printing() done, defined at result1.py:11> result=25>
Upvotes: 0