How do I use async to loop over a list and call a list object's own function

Viewed 2758

How can I loop over a list of objects async and call their function. For example:

class Cat:
    def talk():
        print("Meow")

class Dog:
    def talk():
        print("Woof")


cat = Cat()
dog = Dog()

animal_list = [cat, dog]

# How would I do these async?
for animal in animal_list:
    animal.talk()

This thread, How to use an async for loop to iterate over a list?, recommends using asyncio, but doesn't example how I can have an object call it's own function such as animal.talk()

1 Answers

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.

Related