async
In Python, the async keyword lets you define asynchronous functions, loops, context managers, generators, and iterators. All these objects allow you to write code that performs non-blocking operations, which is particularly useful for I/O-bound and high-level structured network code.
Python async Keyword Examples
Here’s a simple example demonstrating how to use the async keyword:
hello.py
import asyncio
async def greet():
print("Hello")
await asyncio.sleep(1)
print("World!")
asyncio.run(greet())
In this example, greet() is an asynchronous function that you define with the async keyword. Inside this function, the await keyword waits one second using asyncio.sleep(1). Other asynchronous tasks can run during the waiting period, which is the base of the non-blocking behavior.
Python async Keyword Use Cases
- Writing asynchronous functions that can be paused and resumed
- Managing I/O-bound tasks like network requests, file operations, or database queries
- Improving the performance of programs by allowing other tasks to run while waiting for an operation to complete
Related Resources
Tutorial
Python's asyncio: A Hands-On Walkthrough
Explore how Python asyncio works and when to use it. Follow hands-on examples to build efficient programs with coroutines and awaitable tasks.
For additional information on related topics, take a look at the following resources:
- Getting Started With Async Features in Python (Tutorial)
- Asynchronous Iterators and Iterables in Python (Tutorial)
- Python Keywords: An Introduction (Tutorial)
- Hands-On Python 3 Concurrency With the asyncio Module (Course)
- Python's asyncio: A Hands-On Walkthrough (Quiz)
- Getting Started With Async Features in Python (Quiz)
- Asynchronous Iterators and Iterables in Python (Quiz)
- Exploring Keywords in Python (Course)
- Python Keywords: An Introduction (Quiz)