Python

Lesson 10

Async and await boundaries

Await asynchronous work and gather independent calls intentionally so coroutines do not leak out unfinished.

Good Code

profiles.py
import asyncio


async def fetch_profiles(user_ids, api):
    tasks = [api.fetch_profile(user_id) for user_id in user_ids]
    return await asyncio.gather(*tasks)

Bad Code

profiles.py
async def fetch_profiles(user_ids, api):
    profiles = []
    for user_id in user_ids:
        profiles.append(api.fetch_profile(user_id))
    return profiles

Review Notes

What to review

Good Code

The good version collects independent async calls and awaits them together.

Bad Code

The bad version returns coroutine objects instead of profile data. The caller may see confusing values, and the intended I/O may never complete.

Takeaways

  • Calling an async function creates work to await; it does not complete the work by itself.