How to Run an Asyncio Coroutine in Python - Super Fast Python

You can run an asyncio coroutine via the run() function, by awaiting it within another coroutine, or by scheduling it as Task.

In this tutorial, you will discover how to run a coroutine with asyncio in Python.

Let’s get started.

The asyncio module provides coroutine-based concurrency in Python.

It is specifically designed for Asynchronous I/O, also called non-blocking IO and focuses on non-blocking socket programming.

asyncio is often a perfect fit for IO-bound and high-level structured network code.

asyncio – Asynchronous I/O

This is achieved through the async/await syntax in Python.

Coroutines are defined using the “async” keyword, and running coroutines can execute and wait on coroutines using the “await” keyword.

Coroutines are central to asyncio.

As such, how can we run a new coroutine?

How to Run an Asyncio Coroutine

There are three key ways to run an asyncio coroutine, they are:

  1. Call asyncio.run()
  2. Await the Coroutine
  3. Schedule as a Task

Let’s take a closer look at each approach in turn.

Call asyncio.run()

A coroutine can be executed by creating an instance of the coroutine and passing it to the asyncio.run() function.

For example:

...

# create the coroutine

coro = custom_coroutine()

# start the event loop and execute the coroutine

asyncio.run(coro)

This approach to executing a coroutine is typically performed in a single line.

For example:

...

# start the event loop and execute the coroutine

asyncio.run( custom_coroutine())

This will start the asyncio runtime, called the event loop, and execute the coroutine.

It is the primary way that asyncio applications are started.

Await the Coroutine

Another way to run a coroutine is to await it from a running coroutine.

For example:

# defines a custom coroutine

def another_coroutine():

...

# create the coroutine

coro = custom_coroutine()

# execute and wait for the coroutine to finish

await coro

This is typically performed in a single line.

For example:

...

# execute and wait for the coroutine to finish

await custom_coroutine()

Recall that the “await” keyword takes an awaitable.

If we use the await keyword and pass it a new coroutine, it will pause the current coroutine, execute the new coroutine and wait for the new coroutine to complete before resuming.

Schedule as a Task

A coroutine can be wrapped in a Task and executed independently.

This will schedule the coroutine for execution at some future time.

This can be achieved by calling the asyncio.create_task() function from within a coroutine.

For example:

...

# create the coroutine

coro = custom_coroutine()

# wrap in a task and schedule for execution

task = asyncio.create_task(coro)

This is typically performed in a single line.

For example:

...

# wrap in a task and schedule for execution

task = asyncio.create_task(custom_coroutine())

The task will not execute until the event loop has an opportunity to execute the task.

This may be when the current coroutine finishes.

We can also explicitly pause the current coroutine and wait for the task to complete via the await keyword.

This is because a Task is an awaitable, e.g. an object that can be waited on via the await keyword.

For example:

...

# wrap in a task and schedule for execution

task = asyncio.create_task(custom_coroutine())

# wait for the task to complete

await task

Now that we know three ways to execute a coroutine, let’s look at some worked examples.

Example of Calling asyncio.run()

A coroutine can be executed by starting the asyncio event loop and passing the coroutine for execution.

This can be achieved by calling the asyncio.run() function and passing it the coroutine instance.

The example below defines a custom coroutine that takes a message and prints it. The coroutine is then created and passed to the asyncio.run() function for execution.

# SuperFastPython.com

# example of executing a coroutine using the event loop

import asyncio

# custom coroutine

async def custom_coro(message):

    # report the message

    print(message)

# create and execute coroutine

asyncio.run(custom_coro('Hi from a coroutine'))

Running the example creates the coroutine and passed it a message to report.

The coroutine is passed to the asyncio.run() function that starts the asyncio event loop and executes the coroutine.

The message is then reported from the coroutine and the asyncio event loop is shut down.

This highlights how we can run a coroutine directly using the asyncio event loop.


Free Python Asyncio Course

Download your FREE Asyncio PDF cheat sheet and get BONUS access to my free 7-day crash course on the Asyncio API.

Discover how to use the Python asyncio module including how to define, create, and run new coroutines and how to use non-blocking I/O.

Learn more
 


Example of Running a Coroutine by Awaiting

A coroutine can be executed by awaiting it from within another running coroutine.

This can be achieved by creating the new coroutine and using the await keyword.

The example below creates a coroutine and passes it to the asyncio.run() function as in the example above to start the asyncio event loop. The custom coroutine then creates its own second coroutine and awaits it.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

# SuperFastPython.com

# example of executing a coroutine from a coroutine

import asyncio

# another custom coroutine

async def new_coro(message):

    # report the message

    print(message)

# custom coroutine

async def custom_coro(message):

    # execute the new coroutine

    await new_coro('Hi from coroutine within a coroutine')

    # report the message

    print(message)

# create and execute coroutine

asyncio.run(custom_coro('Hi from a coroutine'))

Running the example first creates the custom coroutine with a custom message and starts the asyncio event loop.

The coroutine executes and creates a second coroutine with a different message and awaits it.

This pauses the first coroutine, allowing the second coroutine to execute.

The second coroutine executes, reports its own message then terminates. The first coroutine then continues on and reports its message.

This highlights how we can run a coroutine by calling it from within a coroutine.

Hi from coroutine within a coroutine

Hi from a coroutine

Example of Running a Coroutine as a Task

We can run a coroutine by wrapping it in a task via the asyncio.create_task() function.

This will schedule the coroutine for independent execution and provide a handle on the coroutine.

The example below creates and runs a custom coroutine as per normal. The custom coroutine then creates a second coroutine and then wraps the coroutine in a task. This schedules the coroutine for independent execution. The custom coroutine then waits for the task to be done.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

# SuperFastPython.com

# example of executing a coroutine as a task from a coroutine

import asyncio

# another custom coroutine

async def new_coro(message):

    # report the message

    print(message)

# custom coroutine

async def custom_coro(message):

    # create the new coroutine

    coro = new_coro('Hi from coroutine within a coroutine')

    # wrap the coroutine in a task and schedule for execution

    task = asyncio.create_task(coro)

    # wait for the task to complete

    await task

    # report the message

    print(message)

# create and execute coroutine

asyncio.run(custom_coro('Hi from a coroutine'))

Running the example first creates the custom coroutine with a message and starts the asyncio event loop.

The custom coroutine then creates a second coroutine with another message. It then wraps the coroutine in a task that immediately schedules it for execution.

The custom coroutine then explicitly waits for the task to complete, although this is not required.

The second coroutine executes via the task and reports its message, then is done.

The first coroutine then continues on and reports its message.

Hi from coroutine within a coroutine

Hi from a coroutine


Python Asyncio Jump-Start

Loving The Tutorials?

Why not take the next step? Get the book.

Learn more
 


Further Reading

This section provides additional resources that you may find helpful.

Python Asyncio Books

I also recommend the following books:

Guides

APIs

References

Takeaways

You now know how to run a coroutine using asyncio in Python.

Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.

Photo by Florian Schneider on Unsplash