Restore a patched mapping after an exception with patch.dict
Also published in our primary archive.
A direct answer to “Restore a patched mapping after an exception with patch.dict Python” is: put the override inside a patch.dict context manager. The context manager restores the mapping as it exits, including when the body raises an exception, so cleanup does not depend on reaching manual code after a failure.
This fixture starts with an ordinary in-memory configuration dictionary. Inside patch.dict, it replaces two values and asserts the temporary view. It then raises a local sentinel exception to force exceptional exit. The surrounding except handles only that planned sentinel, after which the final assertion checks the complete original dictionary, not merely one key. The printed observations show the temporary values and restored values deterministically.
By contrast, an assignment followed by restoration code after a possible exception can leave state changed if control never reaches that code. patch.dict scopes changes only to the mapping supplied to it; it does not undo changes to unrelated objects, external services, or effects performed elsewhere in the context. This example intentionally uses neither environment variables nor private configuration. unittest.mock and patch.dict are available in Python 3.3 and later. See the official patch.dict documentation.
AI assistance disclosure: this synthetic in-memory configuration example was drafted with AI assistance.
from unittest.mock import patch
class Sentinel(Exception):
pass
settings = {"mode": "stable", "retries": 3}
try:
with patch.dict(settings, {"mode": "temporary", "retries": 0}):
assert settings == {"mode": "temporary", "retries": 0}
inside = f"{settings['mode']}:{settings['retries']}"
raise Sentinel("planned failure")
except Sentinel:
pass
assert settings == {"mode": "stable", "retries": 3}
restored = f"{settings['mode']}:{settings['retries']}"
print(f"inside={inside}")
print(f"restored={restored}")
inside=temporary:0
restored=stable:3