
Async io in Python is a Python package that can be used to write concurrent codes. What is concurrency? Concurrency is a process where multiple tasks can run in an overlapping manner and can be paused and resumed as they can save their state during these intervals. It is a slightly broader term than parallelism.
Highlights:
- Understanding Concurrency: Concurrency is explained as a process where multiple tasks can run in an overlapping manner, allowing them to be paused and resumed while saving their state. It's highlighted as a broader concept than parallelism.
- Introduction to Async IO in Python: Async IO is introduced as a library package in Python that enables the writing of concurrent and asynchronous code using the
asyncandawaitsyntax. The package can be imported usingimport asyncio, and functions introduced withasyncare termed coroutines.- Setting up Async IO Environment: The process of setting up Async IO in Python is outlined, including the requirement of Python version 3.7 or above and the creation of a virtual environment using tools like
venvorvirtualenv. The installation of async libraries likeaiohttpandaioredisis also demonstrated.- Understanding Coroutines: Coroutines are highlighted as an important aspect of Async IO in Python. They are described as functions that can suspend their execution and pass control to another coroutine task temporarily, allowing concurrent code execution without blocking.
- Utilizing Await/Async Keyword and Event Loop: The usage of
awaitkeyword to suspend coroutine execution until asynchronous operations are completed is explained. Additionally, the concept of an event loop in Async IO Python is demonstrated through an example, showcasing how tasks are executed concurrently.
| Async IO in Python |
| Python -m venv myenv myevn\Scripts\activate //for windows Source myenv/bin/activate //for uniX or macOS |
| Async IO in Python |
| pip install aiohttp aioredis |
| Async IO in Python |
| import asyncio async def hello(): print("Hello") await asyncio.sleep(1) print("World") asyncio.run(hello()) |
| Async IO in Python |
| async def my_coroutine(): # Async code here |
| Async IO in Python |
| async def demo(): # Execution will be paused here and return to demo() when demo1() is ready asy = await demo1() return asy |
| Async IO in Python |
| import asyncio async def task1(): print("Event 1 started") await asyncio.sleep(2) #I/O-bound operation print("Event 1 completed") async def task2(): print("Event 2 started") await asyncio.sleep(1) # Simulate some I/O-bound operation print("Event 2 completed") async def main(): await asyncio.gather(task1(), task2()) # Create and run the event loop asyncio.run(main()) |
Output
| Event 1 started Event 2 started Event 2 completed Event 1 completed |