PythiloLesson 23 of 30 · progress kept in this browser

Context managers

with guarantees cleanup, whichever way a block ends. An object supports it by defining __enter__ and __exit__.

class Timer:
    def __enter__(self):
        return self

    def __exit__(self, kind, err, tb):
        print("done")
        return False  # do not swallow

__exit__ receives details of any exception. A true return value suppresses it, so usually return False.

Your task

Write a context manager temporary_setting(settings, key, value) that sets settings[key] = value for the block, then restores the old value, or removes the key if it did not exist before. It must clean up after an exception and let the exception propagate.