Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python asynchronous context managers code

Practice implementing __aenter__() and __aexit__(), handling asynchronous cleanup and exception behavior, and using async with.

Intermediate ~8 min read

Challenge 1

Wait for the asynchronous setup step, then return the ready label from __aenter__().

python Your answer
import asyncio

class Resource:
    async def __aenter__(self):
        

    async def __aexit__(self, exc_type, exc_value, traceback):
        return False

async def main():
    async with Resource() as value:
        print(value)

asyncio.run(main())

Press Ctrl⌘Enter to check your answer

Challenge 2

Perform asynchronous cleanup, then allow exceptions from the async with block to propagate.

python Your answer
import asyncio

class SafeBlock:
    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        

async def main():
    try:
        async with SafeBlock():
            raise ValueError("problem")
    except ValueError:
        print("propagated")

asyncio.run(main())

Press Ctrl⌘Enter to check your answer

Challenge 3

Suppress only LookupError exceptions after performing an asynchronous exit step.

python Your answer
import asyncio

class IgnoreLookupError:
    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        

async def main():
    async with IgnoreLookupError():
        raise LookupError("ignored")
    print("continues")

asyncio.run(main())

Press Ctrl⌘Enter to check your answer

Challenge 4

Use two asynchronous context managers in one statement, in the shown order.

python Your answer
import asyncio

class Mark:
    def __init__(self, name):
        self.name = name

    async def __aenter__(self):
        print("enter", self.name)

    async def __aexit__(self, exc_type, exc_value, traceback):
        print("exit", self.name)
        return False

async def main():
    
        print("body")

asyncio.run(main())

Press Ctrl⌘Enter to check your answer