A Temporary Setting
Write temp_change(settings, key, value), to be used like this:
python
with temp_change(config, "debug", True):
... # inside the block config["debug"] is True
# after the block config["debug"] has its old value again
- If the key did not exist before, it must be removed again afterwards.
- The old state must be restored even if the block raises an exception, and the exception must still reach the caller.
Understand the problem
Look at what with guarantees.
What does a with statement guarantee?
- The block runs faster
- Cleanup code runs when the block ends, even after an exception
- The block runs in a new thread
A context manager has an entry step (__enter__) and an exit step (__exit__) that always runs when the block ends, whether it finished normally or raised. That is what makes with open(...) close the file in every case.
Which tool turns a generator function with one yield into a context manager?
@functools.wraps@contextlib.contextmanager@property
@contextmanager runs the code before yield on entering, and the code after yield on leaving. Put the restore in a finally: so it also runs when the block raises.
Write the solution
A context manager function.
from contextlib import contextmanager
@contextmanager
def temp_change(settings, key, value):
# Write your code here.
pass
Hint 1: a question to ask yourself
What must you remember before you change the entry, and how do you tell "there was an old value" from "there was none"?
Hint 2: the shape of the answer
Use a marker object for "missing": old = settings.get(key, MISSING). Set the new value, try: yield, and in finally: put the old value back, or delete the key if it was missing.
Reflect
Solution
from contextlib import contextmanager
_MISSING = object()
@contextmanager
def temp_change(settings, key, value):
old = settings.get(key, _MISSING)
settings[key] = value
try:
yield settings
finally:
if old is _MISSING:
del settings[key]
else:
settings[key] = old
Another way: a class with enter and exit
_MISSING = object()
class temp_change:
def __init__(self, settings, key, value):
self.settings, self.key, self.value = settings, key, value
def __enter__(self):
self.old = self.settings.get(self.key, _MISSING)
self.settings[self.key] = self.value
return self.settings
def __exit__(self, exc_type, exc, tb):
if self.old is _MISSING:
del self.settings[self.key]
else:
self.settings[self.key] = self.old
return False
What this tests: context managers, @contextmanager, try / finally, a sentinel object, and the exception-safety of cleanup.
Why finally is essential: without it, an exception in the block skips the restore code and the setting stays changed. With finally, the cleanup runs and the exception continues to the caller.
The sentinel: settings.get(key) returns None both for a missing key and for a key whose value is None. A private object() is never equal to a real value, so it tells the two cases apart.
The class version: __enter__ runs at the start, __exit__(exc_type, exc, tb) at the end. Returning a true value from __exit__ would swallow the exception; return False (or nothing) to let it through.
Real uses: unittest.mock.patch, temporary directories, database transactions, locks, decimal.localcontext.
What an interviewer might ask next: Write a context manager timer() that measures how long its block takes. (Record time.perf_counter() before the yield and after it, in a finally.)
VISIBLE = 3
CASES = [
('cfg = {"debug": False}\nwith temp_change(cfg, "debug", True):\n inside = cfg["debug"]\nresult = (inside, cfg["debug"])', (True, False), 'changed inside, restored after'),
('cfg = {}\nwith temp_change(cfg, "mode", "fast"):\n inside = dict(cfg)\nresult = (inside, cfg)', ({'mode': 'fast'}, {}), 'a new key is removed afterwards'),
('cfg = {"a": 1}\ntry:\n with temp_change(cfg, "a", 2):\n raise RuntimeError("boom")\nexcept RuntimeError:\n pass\nresult = cfg["a"]', 1, 'restored even after an exception'),
('cfg = {"a": 1}\ntry:\n with temp_change(cfg, "a", 2):\n raise KeyError("x")\nexcept KeyError:\n result = "reached the caller"', 'reached the caller', 'the exception still propagates'),
('cfg = {"a": None}\nwith temp_change(cfg, "a", 5):\n pass\nresult = ("a" in cfg, cfg["a"])', (True, None), 'an old value of None is restored, not deleted'),
('cfg = {"a": 1, "b": 2}\nwith temp_change(cfg, "a", 9):\n pass\nresult = cfg', {'a': 1, 'b': 2}, 'other keys are untouched'),
('cfg = {"a": 1}\nwith temp_change(cfg, "a", 2):\n with temp_change(cfg, "a", 3):\n deep = cfg["a"]\n mid = cfg["a"]\nresult = (deep, mid, cfg["a"])', (3, 2, 1), 'nested use'),
('cfg = {}\ntry:\n with temp_change(cfg, "x", 1):\n raise ValueError\nexcept ValueError:\n pass\nresult = cfg', {}, 'a new key is removed after an exception too'),
]