Editor

Refactor to Async Pattern

Advanced · Refactor · from Python Async/Await: Write Non-Blocking Code from Scratch

From the lesson: Python Async/Await: Write Non-Blocking Code from Scratch

Imagine you're a chef in a busy kitchen. You don't stand and watch the oven for 20 minutes while your pasta boils on another burner. Instead, you start the oven, move to the pasta, then check the salad -- all without waiting idle. That's exactly what asynchronous programming does for your code.

Read the lesson

The synchronous code below processes users sequentially. Refactor it to use async def syntax that *would* run concurrently with asyncio.gather(). Keep the same logic but:

1. Make fetch_user an async def

2. Make process_all an async def that uses await on each fetch_user call

3. After the definitions, print Refactored to async to confirm.

def fetch_user(user_id):
return {'id': user_id, 'name': f'User_{user_id}'}
def process_all(ids):
results = []
for uid in ids:
user = fetch_user(uid)
results.append(user)
return results
print(process_all([1, 2, 3]))

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
import inspect print(inspect.iscoroutinefunction(fetch_user)) print(inspect.iscoroutinefunction(process_all))Refactored to async True True

More Async and Await exercises

All Python exercises · 50 practice problems · Advanced Python quiz