@contextlib.contextmanager<EOL>def restore_dict_kv(a_dict, key, copy_func=copy.deepcopy):
exists = False<EOL>if key in a_dict:<EOL><INDENT>backup = copy_func(a_dict[key])<EOL>exists = True<EOL><DEDENT>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>if exists:<EOL><INDENT>a_dict[key] = backup<EOL><DEDENT>else:<EOL><INDENT>a_dict.pop(key, None)<EOL><DEDENT><DEDENT>
Backup an object in a with context and restore it when leaving
    the scope.

    :param a_dict:
      associative table
    :param: key
      key whose value has to be backed up
    :param copy_func: callbable object used to create an object copy.
    default is `copy.deepcopy`