Fix the Async Bug
Advanced · Fix the bug · 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 lessonThe code below tries to define an async context manager but has two bugs. Fix them so that async with AsyncResource(): works and a block inside it shows:
Entering context
Doing work
Exiting contextKeep the last line, which prints Context manager ready.
class AsyncResource:
def __aenter__(self):
print('Entering context')
return self
def __aexit__(self, exc_type, exc_val, exc_tb):
print('Exiting context')
return False
print('Context manager ready')
What Check runs
Your code runs first, then each of these lines. The output must match exactly.
| Runs | Expected output |
|---|---|
| import inspect print(inspect.iscoroutinefunction(AsyncResource.__aenter__)) print(inspect.iscoroutinefunction(AsyncResource.__aexit__)) | Context manager ready True True |
| async with AsyncResource(): print('Doing work') | Context manager ready Entering context Doing work Exiting context |
More Async and Await exercises
- Define a CoroutineAdvanced
- Predict the Coroutine OutputAdvanced
- Build an Async IteratorAdvanced
- Gather Concurrent ResultsAdvanced
- Refactor to Async PatternAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz