libb.replacekey
- replacekey(d, key, newval)[source]
Context manager for temporarily patching a dictionary value.
- Parameters:
d (dict) – Dictionary to patch.
key – Key to temporarily replace.
newval – Temporary value to set.
Basic Usage:
>>> f = dict(x=13) >>> with replacekey(f, 'x', 'pho'): ... f['x'] 'pho' >>> f['x'] 13
If the dict does not have the key set before, we return to that state:
>>> import os, sys >>> rand_key = str(int.from_bytes(os.urandom(10), sys.byteorder)) >>> with replacekey(os.environ, rand_key, '22'): ... os.environ[rand_key]=='22' True >>> rand_key in os.environ False