The gather() function of asyncio module in Python

The gather() function of asyncio module in Python executes a collection of awaitable objects and returns their results aggregated upon awaiting.

Asyncio Updated 27 May 2022 1 min read

Overview

  • The gather() function starts and runs multiple awaitables concurrently, grouping them as a Future.
  • Awaiting on the returned Future object runs the awaitables to completion and returns the results.

Example

python
# An example Python program that

            # runs multiple coroutines concurrently

            # using asyncio.gather()

            import asyncio

# A coroutine that generates odd numbers

            async def oddgen(limit):

                cur = 1

                print("From oddgen:%d"%cur)

                while cur < limit:

                    cur = cur + 2

                    print("From oddgen:%d"%cur)

                    await asyncio.sleep(0)

                return cur

# A coroutine that generates even numbers

            async def evengen(limit):

                cur = 0

                print("From evengen:%d"%cur)

                while cur < limit:

                    cur = cur + 2

                    print("From evengen:%d"%cur)

                    await asyncio.sleep(0)

                return cur

# Coroutine that is bootstrapped by

            # the asyncio event loop

            async def main():

                res = await asyncio.gather(oddgen(5), evengen(10))

                print("Results from asyncio.gather():%s"%res)

el = asyncio.new_event_loop()

            asyncio.set_event_loop(el)

            asyncio.run(main())

Output

Output
From oddgen:1

From oddgen:3

From evengen:0

From evengen:2

From oddgen:5

From evengen:4

From evengen:6

From evengen:8

From evengen:10

Results from asyncio.gather():[5, 10]