Tutorials Logic, IN info@tutorialslogic.com

Python async and await: Write Event Loop Code

Async Await

async and await let Python pause one task while waiting and continue another task in the same event loop.

Async code is useful for I/O-heavy work such as many network requests, sockets, or cooperative background tasks.

Do not use async just because it looks advanced. Use it when libraries and workload fit the event-loop model.

Async Function

An async def function returns a coroutine. It runs when awaited or passed into the event loop.

  • Use async def to define a coroutine function.
  • Use await inside async code to pause for another awaitable.
  • Use asyncio.run for a simple program entry point.

Run a Coroutine

Run a Coroutine
import asyncio

async def greet():
    await asyncio.sleep(0)
    return "Hello async"

message = asyncio.run(greet())
print(message)
Output
Hello async

asyncio.run starts the event loop and returns the coroutine result.

Concurrent Awaits

asyncio.gather waits for multiple awaitable tasks and returns their results together.

  • Use gather when tasks can wait independently.
  • Keep blocking functions out of async code.
  • Use async libraries for real network work.

Gather Results

Gather Results
import asyncio

async def load(name):
    await asyncio.sleep(0)
    return name.upper()

async def main():
    results = await asyncio.gather(load("csv"), load("json"))
    print(results)

asyncio.run(main())
Output
['CSV', 'JSON']

Both coroutines are scheduled and gathered by the event loop.

Before you move on

Can You Use Async Await?

5 checks
  • You can explain coroutine, await, and event loop in plain language.
  • You can run one coroutine with asyncio.run.
  • You can await another async function.
  • You can gather multiple awaitables.
  • You can decide when async is more appropriate than normal sequential code.

Await Flow Traps

  • Calling async functions like normal functions

    Await the coroutine or run it through asyncio.run.
  • Putting blocking work in async code

    Use async-compatible libraries or keep blocking work outside the event loop.
  • Using async for every beginner script

    Use normal functions until the program has real concurrent I/O needs.

Try this next

Await Slow Tasks

0 of 3 completed

  1. Create load_user and load_orders coroutines that return strings, then gather both.
  2. Write one sentence explaining what happens when a coroutine reaches await.
  3. List one task that fits threading and one task that fits async.

Questions About Async Await

Only for the right kind of waiting-heavy workload. It does not automatically speed up ordinary calculations.

You usually get a coroutine object instead of the final result, and the intended work may not run.

Advanced programs can, but beginners should learn each model separately first.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.