code: def safe_temp_edit(filename):
    
    with temporary_file() as tmp_file:
      try:
        shutil.copyfile(filename, tmp_file.name)
        yield filename
      finally:
        shutil.copyfile(tmp_file.name, filename)
docs: Safely modify a file within context that automatically reverts any changes afterwards
  
    The file mutatation occurs in place. The file is backed up in a temporary file before edits
    occur and when the context is closed, the mutated file is discarded and replaced with the backup.
  
    WARNING: There may be a chance that the file may not be restored and this method should be used
    carefully with the known risk.