Python Forum
How to get coroutine from a task, and an object from a coroutine? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to get coroutine from a task, and an object from a coroutine? (/thread-16980.html)



How to get coroutine from a task, and an object from a coroutine? - AlekseyPython - Mar-23-2019

Python 3.5

I have an object, one of the methods of which is coroutine:
class A:
    def __init__(self):
        self.number = random.random()

    async def my_method(self):
       asyncio.sleep(1)
       print('Hello, world!')
I create task:
async def add_task(tasks:list):
    a = A()
    coro = a.my_method()
    task = asyncio.create_task(coro)
    tasks.append(task)
How can I get object 'a' from tasks[0]?


RE: How to get coroutine from a task, and an object from a coroutine? - DeaD_EyE - Mar-23-2019

Calls to a async code must be awaited somewhere.
Calling an async function returns a coroutine object.
This can be send to the event loop or awaited.

To gather coroutines, you can use asyncio.gather(*coros).

import random
import asyncio
import time

class A:
    def __init__(self):
        self.number = random.random()
    async def my_method(self):
        # await for the coroutine
        await asyncio.sleep(1)
        # is later collected by asyncio.gather
        return 'Hello World'


async def worker(tasks):
    # create the coroutines by calling the async method
    # don't await for them, gather is doing this
    coros = [task.my_method() for task in tasks]
    # gather runs all tasks together asynchronous
    # and returns the return values as a list
    # await is needed here, to run the
    # gather function
    return await asyncio.gather(*coros)


# create some classes
objects = [A() for _ in range(3)]
# now a list with 20 instances of A
coro = worker(objects) # code is currently not running

loop = asyncio.get_event_loop()

# this runs the asynchronous code
# in the event loop
# after is has been finished all tasks
# the method returns the results
# in this case a list, because the use of gather
results = loop.run_until_complete(coro)
print(results)

# another example with one task
my_a = A()
result = loop.run_until_complete(my_a.my_method())
# this time result is a string
print(result)


# here synchronous code
Maybe you have to put return await in different lines. I use Python 3.7.

return await asyncio.gather(*coros)
result = await asyncio.gather(*coros)
return results



RE: How to get coroutine from a task, and an object from a coroutine? - AlekseyPython - Mar-23-2019

I balance the load between several tasks, each of which has a lot of running coruntines. Therefore, I want to receive an object, and write to one of its attributes a message about the termination of the activity of the coruntine (which it can easily read through 'self').