Python async
The async keyword defines an asynchronous function in Python. Asynchronous functions let a program handle multiple tasks concurrently without waiting for each to finish, improving efficiency and enabling non-blocking execution.
Syntax
import asyncio
async def function_name(parameters):
# Function body
await #awaitable code
In the syntax:
import asyncio: Imports Python’s built-in library for running and managing asynchronous tasks.async: Theasynckeyword is declared beforedefto define an asynchronous function (coroutine).await: Used inside an async function to pause execution until the awaited coroutine or awaitable object completes.
Parameters:
Same as a regular function, any number of positional or keyword arguments.
Return value:
Returns a coroutine object, which must be awaited (using await) to get the actual result.
Note: If an
asyncfunction doesn’t contain anyawaitstatements, it will still be valid but won’t perform any asynchronous operations.
Example 1
In this example, the async function hello() prints the first half of ‘Hello world!’, waits 3 seconds, and then prints the second half:
import asyncioasync def hello():print("Hello")await asyncio.sleep(3) # Pauses for 3 secondsprint("world!")
Here is the output of this code:
Helloworld!
Example 2
In this example, the brew_tea and make_toast async functions start running at the same time. make_toast finishes first in 3 seconds, while brew_tea takes 5 seconds to complete. The program waits for both tasks to finish, then prints their results together after a total of 5 seconds:
import asyncioasync def brew_tea():print("Start brewing tea")await asyncio.sleep(5) # Pauses for 5 secondsreturn "The tea is ready!"async def make_toast():print("Start making toast")await asyncio.sleep(3) # Pauses for 3 secondsreturn "The toast is ready!"async def make_breakfast():batch = asyncio.gather(brew_tea(), make_toast())tea_complete, toast_complete = await batchprint(tea_complete)print(toast_complete)result = asyncio.run(make_breakfast())print(result)
The output of this code is:
Start brewing teaStart making toastThe tea is ready!The toast is ready!None
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours