libb.replaceattr
- replaceattr(obj, attrname, newval)[source]
Context manager for temporarily monkey patching an object attribute.
- Parameters:
obj – Object to patch.
attrname (str) – Attribute name to temporarily replace.
newval – Temporary value to set.
Basic Usage:
>>> class Foo: pass >>> f = Foo() >>> f.x = 13 >>> with replaceattr(f, 'x', 'pho'): ... f.x 'pho' >>> f.x 13
If the obj did not have the attr set, we remove it:
>>> with replaceattr(f, 'y', 'boo'): ... f.y=='boo' True >>> hasattr(f, 'y') False