Hard: Advanced Interview · Problem 74 of 82

A Temporary Setting

HardErrors and FilesPython

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?

  1. The block runs faster
  2. Cleanup code runs when the block ends, even after an exception
  3. 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?

  1. @functools.wraps
  2. @contextlib.contextmanager
  3. @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.)