Python Forum
How to get coroutine from a task, and an object from a coroutine?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get coroutine from a task, and an object from a coroutine?
#2
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: How to get coroutine from a task, and an object from a coroutine? - by DeaD_EyE - Mar-23-2019, 10:39 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Coroutine was never awaited error bucki 1 693 Sep-23-2023, 08:17 PM
Last Post: deanhystad
  count certain task in task manager[solved] kucingkembar 2 1,173 Aug-29-2022, 05:57 PM
Last Post: kucingkembar
  Schedule a task and render/ use the result of the task in any given time klllmmm 2 2,146 May-04-2021, 10:17 AM
Last Post: klllmmm
  How to create a task/import a task(task scheduler) using python Tyrel 7 3,808 Feb-11-2021, 11:45 AM
Last Post: Tyrel
  How to add coroutine to a running event loop? AlekseyPython 1 8,209 Mar-21-2019, 06:04 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020