Master Python Async: Boost Performance with asyncio, async/await, and Tasks
This guide explains Python asynchronous programming using the asyncio library, covering async functions, coroutine objects, the event loop, await syntax, task creation, and concurrent execution with asyncio.run, create_task, and gather to improve I/O‑bound performance.
Python asynchronous programming uses non‑blocking execution to run multiple tasks concurrently, greatly improving efficiency for I/O‑intensive workloads. The core of Python async is the asyncio module, with async and await keywords.
1. Define async functions with async def
def hello():
return 'hello'
print(hello) # <function hello at 0x...>
async def hello():
return 'hello'
print(hello) # <function hello at 0x...>The first is a regular function; the second uses async def and returns a coroutine object when called.
2. Calling an async function returns a coroutine
def hello():
return 'hello'
print(hello()) # hello
async def hello():
return 'hello'
print(hello()) # <coroutine object hello at 0x...>
# RuntimeWarning: coroutine 'hello' was never awaitedCalling an async function without await yields a coroutine object and triggers a warning.
3. What a coroutine is
A coroutine is a special function that can be paused and resumed, allowing multiple tasks to run concurrently.
4. Run a coroutine directly with asyncio.run()
async def hello():
print('running hello coroutine')
return 'hello'
asyncio.run(hello()) # running hello coroutine asynciois part of the Python standard library; no extra installation is needed.
5. Use await to execute a coroutine
import asyncio
async def hello():
print('running hello coroutine')
return 'hello'
async def main():
x = await hello()
print(x)
asyncio.run(main())
# running hello coroutine
# hello awaitpauses the current coroutine until the awaited coroutine finishes, then returns its result.
6. await can only be used inside async def functions
import asyncio
async def hello():
return 'hello'
def test():
x = await hello() # SyntaxError: 'await' outside async functionAttempting to use await in a regular function raises a syntax error.
7. Wrap coroutines as tasks with asyncio.create_task()
import asyncio
async def my_coroutine():
print("开始执行")
await asyncio.sleep(1)
print("执行完成")
async def main():
task1 = asyncio.create_task(my_coroutine())
task2 = asyncio.create_task(my_coroutine())
await task1
await task2
asyncio.run(main())Tasks represent running coroutines and provide status information.
8. Run multiple coroutines concurrently with asyncio.gather()
import asyncio
async def hello():
print('start')
await asyncio.sleep(1)
print('end')
async def main():
await asyncio.gather(hello(), hello(), hello())
asyncio.run(main())
# start
# start
# start
# end
# end
# end asyncio.gatherschedules the coroutines to run in parallel, so all "start" messages appear together, followed by all "end" messages after the sleep.
Summary
Python's async programming, powered by the asyncio library, provides native coroutine support, making concurrent I/O tasks more efficient and concise. Introduced in Python 3.4 and refined with async / await syntax in 3.5+, asyncio enables event‑loop‑driven execution without the overhead of traditional multithreading.
asynciouses an event loop to schedule tasks, allowing asynchronous I/O operations to proceed without blocking the whole program, achieving high concurrency in a single thread.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
