TL;DR: I want to create asyncio task/coroutine and get the return values to be assigned in a var.
-
I found this question Getting values from functions that run as asyncio tasks Which seems to talk about a similar issue, but the sintax has changed a lot in the asyncio module that I not even sure if it's related. [I'm on Python 3.7.2]
Sample code for me to explain what I'm trying to do:
async def s(f):
func = {
1: op1,
2: op2,
3: op3
}.get(f,False)
var = func(f)
return var
def op1(f):
print('Op1',f+f)
return f+f
def op2(f):
print('Op2', f*f)
return f*f
def op3(f):
print('Op3', f**f)
return f**f
async def main():
task1 = asyncio.create_task(s(1))
task2 = asyncio.create_task(s(3))
print(f"started at {time.strftime('%X')}")
await task1
await task2
print(task1,task2)
print(f"finished at {time.strftime('%X')}")
The main() is a example coroutine from docs https://docs.python.org/3/library/asyncio-task.html#coroutines
The s() is supposed to be a switch which will select the proper function (one of op1,op2,op3) for the scenario, run the function and RETURN the result, (from what I expected) to be assigned to task1/task2.
What is actually assigned to the task1/task2 is:
<Task finished coro=<s() done, defined at C:\...\test.py:17> result=2>
<Task finished coro=<s() done, defined at C:\...\test.py:17> result=27>
As you can see, the return is stored in 'result' (attribute? var?) but not directly assigned to the var.
I need either: Assign the return directly to the var OR a way to access the 'result' and assign it to a var where I can further manipulate.
BTW: print(task1.result) returns this:
<built-in method result of _asyncio.Task object at 0x0000028592DDA048>
print(task1.result()).