Async Programming with asyncio
Master coroutines, await, event loops, concurrent tasks, cancellation, and non-blocking I/O in Python.
In this lesson, you will learn
- ✓Explain asynchronous programming, coroutines, awaitables, and the event loop.
- ✓Distinguish defining a coroutine, creating a coroutine object, and executing it.
- ✓Use asyncio.run(), asyncio.sleep(), asyncio.create_task(), and asyncio.gather().
- ✓Predict which statements execute before and after an await expression.
- ✓Explain why blocking operations can prevent other coroutines from making progress.
- ✓Handle exceptions and cancellation in asynchronous tasks.
- ✓Choose between asyncio, threading, and multiprocessing for appropriate workloads.
1. What is asynchronous programming?
A normal synchronous function runs when it is called and returns when its work finishes or it raises an exception. If it waits for a slow operation, the current flow of execution normally waits too.
Asynchronous programming is a way to organize work so a task can suspend while waiting for an operation and allow other tasks to make progress. It is particularly useful for I/O-bound programs, such as clients that communicate with multiple servers.
Python's asyncio library provides infrastructure for asynchronous programming. The event loop coordinates asynchronous tasks and resumes them when their awaited operations can make progress.
Concurrency does not necessarily mean parallel execution. Multiple asyncio tasks generally make progress by yielding control to the same event loop. This is different from running Python code simultaneously on multiple CPU cores.
The central idea is cooperative scheduling: a coroutine must reach an appropriate suspension point, usually an await expression, before the event loop can run other tasks on its behalf. A coroutine that performs long-running synchronous work without yielding can delay every other task on that event loop.
Run a simple asynchronous program
async def defines an asynchronous function, also called a coroutine function. asyncio.run(main()) creates and manages an event loop for this standalone program, runs the main coroutine, and returns when it finishes. The first print executes before the await expression. asyncio.sleep(0) is an asynchronous operation that suspends the current coroutine and gives the event loop an opportunity to run other work. After the coroutine resumes, the second print displays End. There are no other tasks in this example, so the visible output is Start followed by End.
Note
2. Coroutines, await, and the event loop
A coroutine function is defined with async def. Calling it creates a coroutine object; it does not immediately execute the function body to completion.
A coroutine object must be awaited, scheduled as a task, or otherwise driven by an appropriate asynchronous runtime. In a typical standalone program, asyncio.run() drives the top-level coroutine.
The await keyword is used inside an async function to wait for an awaitable, such as another coroutine or an asyncio task. When the awaited operation suspends, control can return to the event loop so it can run other ready work.
An event loop is the component that manages asynchronous execution and coordinates callbacks, tasks, and I/O readiness. Most application code should use asyncio's high-level APIs rather than manually creating and managing event loops.
A coroutine that returns a value supplies that value to the code that awaits it. Exceptions raised by the coroutine can also propagate to the awaiting code unless they are handled.
Creating a coroutine object does not run its body
Calling answer() creates a coroutine object, but the body has not started executing. Therefore, Calculating is not printed. The next statement prints Coroutine created. close() closes the coroutine without starting its body. This avoids leaving the unawaited coroutine pending in this demonstration. In ordinary application code, do not create coroutine objects and abandon them. Await them or schedule them appropriately.
3. Run tasks concurrently with create_task() and gather()
Awaiting one coroutine before starting the next can make asynchronous operations run sequentially. If independent operations can overlap, schedule them as tasks or use a suitable higher-level API.
asyncio.create_task(coro) schedules a coroutine to run as an asyncio Task. The event loop can then make progress on that task when the current coroutine yields.
asyncio.gather() accepts awaitables and waits for them to complete, returning their results in the order the awaitables were supplied. Their completion order can be different from their argument order.
Concurrency is useful when tasks spend time waiting. It does not guarantee that every task starts or finishes in a particular order. If order matters, coordinate tasks explicitly.
When creating tasks, ensure they are awaited or otherwise managed. Unmanaged tasks may still be running when the surrounding code finishes, and their exceptions can be overlooked.
Run two waiting tasks concurrently
gather() schedules the supplied coroutine operations and waits for them all to finish. Both tasks begin when the event loop runs them. Their initial messages appear before either sleep finishes in this example. Task B waits for a shorter duration than task A, so B finishes first under the stated delays. gather() returns results in input order, not completion order. Therefore, the result list is ['A', 'B'] even though B finishes first. The example illustrates cooperative concurrency. The delays are deliberately different so the completion order is clear.
Note
4. Blocking operations and common async pitfalls
A major async mistake is calling a blocking function inside a coroutine. For example, time.sleep(2) blocks the event-loop thread for approximately two seconds. Other tasks on that loop cannot run during that blocking period.
Use await asyncio.sleep(2) when you need an asynchronous delay. For network access, use a library that supports asynchronous I/O rather than assuming a synchronous client becomes asynchronous merely because it is called inside async def.
Not every function can be awaited. await must be followed by an awaitable expression. Calling a normal function that returns an integer or string and trying to await that value raises TypeError.
Calling asyncio.run() from a thread that already has a running event loop, such as inside a typical notebook or asynchronous server handler, raises RuntimeError. In an async function, normally use await on the coroutine instead of nesting asyncio.run().
An async function that performs a long CPU-bound calculation without yielding can also monopolize the event loop. Asynchronous I/O does not automatically turn CPU-heavy work into parallel computation.
Do not block the event loop with time.sleep()
create_task() schedules bad_task(), but scheduling does not mean the task executes in parallel on another thread. When bad_task() begins, time.sleep(1) blocks the event-loop thread. The event loop cannot run other_task() during that blocking sleep. Only after bad_task() finishes can the event loop run other_task(). This is an intentionally inefficient example. Replace blocking waits with asynchronous APIs when possible.
Caution
5. Exceptions, cancellation, and choosing the right tool
Asynchronous code still needs normal error handling. If a coroutine raises an exception, awaiting it can propagate that exception to the caller. Use try and except around the await expression when you can recover from a known failure.
A task can be cancelled with Task.cancel(). Cancellation is cooperative: asyncio normally injects CancelledError into the coroutine at an appropriate suspension point. Coroutines should clean up resources when cancelled and should generally allow cancellation to propagate after cleanup.
Do not treat cancellation as a normal successful result. If a task owns a resource, use appropriate cleanup, such as a try/finally block or an asynchronous context manager.
asyncio is well suited to large numbers of concurrent I/O operations when the libraries support asynchronous APIs. threading is often convenient when using blocking I/O libraries or when integrating with thread-based APIs. multiprocessing can help with CPU-bound work that benefits from multiple processes.
These are guidelines, not absolute rules. The best approach depends on the workload, library support, resource constraints, and complexity. For a small sequential program, synchronous code may be simpler and entirely appropriate.
Handle an exception from an awaited coroutine
fetch_value() raises ValueError when it runs. The exception propagates through await to the try block in main(). The matching except clause catches the error and binds it to error. The program prints the message rather than allowing this ValueError to terminate the top-level coroutine.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Assuming calling an async function immediately runs it to completion.
Why it happens: Calling an async function creates a coroutine object; it must be awaited or scheduled for its body to execute.
Key takeaway: Calling a coroutine function creates a coroutine object. Await it, schedule it as a task, or run it through an appropriate asynchronous runtime.
#2 Thinking async def automatically makes code concurrent.
Why it happens: async def defines a coroutine function but does not create concurrency by itself; concurrency requires yielding control and coordinating multiple tasks.
Key takeaway: Coroutines only overlap when the program's structure and scheduling allow it. Sequentially awaiting one operation before starting another can keep the work sequential.
#3 Using time.sleep() inside an asynchronous task.
Why it happens: time.sleep() blocks the event-loop thread and prevents other tasks from progressing; use await asyncio.sleep() for asynchronous waiting.
Key takeaway: Use await asyncio.sleep() for an asynchronous delay. For blocking I/O, prefer an asynchronous library or move suitable blocking work to a thread.
#4 Awaiting an ordinary value such as an integer.
Why it happens: await requires an awaitable such as a coroutine or task, not a plain integer or other ordinary value.
Key takeaway: await requires an awaitable expression, such as a coroutine or Task. A regular function's return value cannot be awaited merely because the caller is asynchronous.
#5 Calling asyncio.run() inside a running event loop.
Why it happens: asyncio.run() manages a new event loop and cannot be nested inside an already running loop; await the coroutine in the existing loop instead.
Key takeaway: In an async function, await the coroutine. Use asyncio.run() as the high-level entry point for a standalone program when there is no running event loop in the current thread.
#6 Assuming asyncio runs CPU-heavy Python code on multiple cores automatically.
Why it happens: Asyncio concurrency primarily helps with cooperative I/O waiting; CPU-bound Python work generally needs a process pool, native code, or another suitable strategy.
Key takeaway: Asyncio coordinates cooperative concurrency; it does not by itself parallelize CPU-bound Python calculations. Consider a process pool when appropriate.
#7 Creating tasks without awaiting or otherwise managing them.
Why it happens: Created tasks need to be awaited, grouped, cancelled, or otherwise managed so exceptions and unfinished work are not lost.
Key takeaway: Keep track of tasks and retrieve their results. Use gather(), await each task, or an appropriate task-management structure.
#8 Ignoring cancellation and cleanup.
Why it happens: Cancellation is delivered to a task as an exception at an await point, so cleanup and cancellation propagation should be handled deliberately.
Key takeaway: Use try/finally or asynchronous context managers to release resources. Handle CancelledError only when needed and preserve cancellation semantics.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is asyncio in Python?
Q2:What is the difference between a coroutine function and a coroutine object?
Q3:What does await do?
Q4:What is an event loop?
Q5:What is the difference between await and asyncio.create_task()?
Q6:What is the difference between asyncio.gather() and sequential awaits?
Q7:Why should time.sleep() not be used inside an async function?
Q8:Does asyncio make CPU-bound code run in parallel?
Q9:When would you choose asyncio instead of threading?
Q10:How does cancellation work in asyncio?
Key takeaways
- async def defines a coroutine function; calling it creates a coroutine object.
- await waits for an awaitable and can give the event loop an opportunity to run other tasks.
- asyncio.run() is a high-level entry point for running a top-level coroutine in a standalone program.
- asyncio.create_task() schedules a coroutine as an independent task, while asyncio.gather() coordinates multiple awaitables.
- Concurrency does not guarantee parallel execution or a particular task completion order.
- Blocking operations such as time.sleep() can stall the event loop.
- Handle exceptions, cancellation, task lifetimes, and resource cleanup deliberately.
- Choose asyncio, threading, multiprocessing, or synchronous code according to the actual workload and library support.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: