@contextlib.contextmanager<EOL>def swap_item(obj, item, new_val):
if item in obj:<EOL><INDENT>real_val = obj[item]<EOL>obj[item] = new_val<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>obj[item] = real_val<EOL><DEDENT><DEDENT>else:<EOL><INDENT>obj[item] = new_val<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>del obj[item]<EOL><DEDENT><DEDENT>
Temporary swap out an item with a new object.

    Usage:
        with swap_item(obj, "item", 5):
            ...

        This will set obj["item"] to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `item` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.