Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 7 · Memory, GC, modern typingcontextlib.ExitStack — dynamic context-manager compositionpredict120 / 161
+150 XP
Task
📝 **Task:** Predict the exact output. Three nested context managers are pushed onto an ExitStack, then the body runs, then ExitStack exits in LIFO order. The events list captures the order of __enter__, body work, and __exit__. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from contextlib import ExitStack


events: list[str] = []


class Tracked:
    def __init__(self, name: str) -> None:
        self.name = name

    def __enter__(self) -> "Tracked":
        events.append(f"enter {self.name}")
        return self

    def __exit__(self, *exc: object) -> bool:
        events.append(f"exit {self.name}")
        return False


with ExitStack() as stack:
    a = stack.enter_context(Tracked("A"))
    b = stack.enter_context(Tracked("B"))
    c = stack.enter_context(Tracked("C"))
    events.append("body")

for e in events:
    print(e)

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…