Restore a patched attribute reliably
A patch changes what code looks up for the duration of a test. A context manager makes that duration explicit and restores the previous value when the block exits, including when an exception escapes the block.
Patch the object or module where the consumer actually reads the attribute. Changing another alias may leave the original reference untouched. A scoped patch is preferable to manual assignment followed by cleanup because an early failure cannot skip restoration. Verify the restored state too, especially when several tests share a dependency object.
from unittest.mock import patch
class Settings:
mode = "live"
with patch.object(Settings, "mode", "test"):
print(Settings.mode)
print(Settings.mode)Your task
Implement temporary_value(obj,value): temporarily patch obj.mode to value, record it, exit the context, and return (temporary_value,restored_value). Preserve the original attribute after each call.
The explanation opens here once every check passes.