Make the talk functions async otherwise there's no point using asyncio
.
class Cat:
async def talk():
print("Meow")
class Dog:
async def talk():
print("Woof")
cat = Cat()
dog = Dog()
animal_list = [cat, dog]
Create a list (Iterable) of coroutines returned by animal.talk()
.
Either coroutines = map(lambda animal : animal.talk(), animal_list)
or
coroutines = [animal.talk() for animal in animal_list]
will do.
Then finally scheduled the list of coroutines for execution.
# This returns the results of the async functions together.
results = await asyncio.gather(coroutines)
# This returns the results one by one.
for future in asyncio.as_completed(coroutines):
result = await future
cat.talk()
and dog.talk()
will be executed asynchronously, which means the order of their execution is not guaranteed, and may be run on different threads. But here the talk
function is so simple that it will look like it's run synchronously, and confers no real benefits.
But if talk
involved making a network request or a long, heavy computation, and the animal_list
were very long, doing it this way can help with the performance.