Editor

A Context Manager That Cleans Up

Advanced · Write the code · from 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

From the lesson: 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

Fifty problems, each with a code editor and real tests. Write your solution, press Check, and see exactly which cases pass. Stuck? Hints reveal one at a time, and the solution unlocks once you have checked at least once. Your code and progress are saved in this browser.

Read the lesson

Write a context manager temporarily(obj, name, value) that sets the attribute obj.name = value inside a with block and always restores the original value afterwards, even if the block raises an error.

with temporarily(settings, "debug", True):
    ...   # settings.debug is True here
# settings.debug is back to what it was
from contextlib import contextmanager
@contextmanager
def temporarily(obj, name, value):
pass
Solution unlocks after your first Check

What Check runs

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

RunsExpected output
class Settings: debug = False s = Settings() with temporarily(s, "debug", True): print("inside:", s.debug) print("after:", s.debug)inside: True after: False
class Settings: level = 1 s = Settings() try: with temporarily(s, "level", 99): raise RuntimeError("boom") except RuntimeError: pass print("restored:", s.level)restored: 1

More practice problems

All Python exercises · 50 practice problems