Commit configuration without partial writes
Stage a complete file and replace it only after serialization succeeds.
Protect the previous good file
Opening a configuration with mode w truncates it immediately. If serialization or a later write fails, the old contents may already be gone. Build the entire JSON text first, write it to a temporary file in the destination directory, close that file, and use os.replace to commit it.
Keeping the temporary file beside the destination avoids a cross-filesystem rename in ordinary local use. This browser exercise checks replacement semantics in its virtual filesystem. It does not promise crash durability on every host filesystem; production tools may additionally need flushing, permissions management, backups and coordination between writers.
A no-op should really do nothing
If the existing object already matches the requested configuration, return without rewriting it. This preserves its modification time and avoids triggering downstream jobs unnecessarily. Compare canonical JSON, including value types, instead of formatting or raw whitespace.
Treat malformed existing configuration as an error rather than overwriting evidence of a problem. Reject a non-object target and invalid requested values before creating a temporary file.
Use finally to clean up a staged file when replacement fails. Re-raise the underlying exception so the caller knows the operation did not commit. Tests will deliberately fail the replacement step and inspect both the original file and the directory afterwards.
import json
payload = json.dumps({"owner":"Zoë","workers":4}, ensure_ascii=False, sort_keys=True, allow_nan=False)
print(payload)
Put it into practice.
Define write_config(path, settings), returning True only when a file is created or changed. Require settings and any existing JSON content to be objects; reject non-finite values and malformed JSON with ValueError. Canonical JSON equality uses sorted keys and distinguishes 1 from 1.0 and False from 0. An unchanged target must retain its exact bytes and modification time. For a change, stage UTF-8 JSON in a temporary file in the same directory, close it, then commit with os.replace. If replacement fails, preserve the original file, remove the temporary file and propagate the exception. The parent directory already exists.
See an explained solution
import json, os, tempfile
from pathlib import Path
def write_config(path, settings):
if not isinstance(settings, dict):
raise ValueError("Settings must be an object")
encode = lambda value: json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)
payload = encode(settings) + "\n"
target = Path(path)
if target.exists():
previous = json.loads(target.read_text(encoding="utf-8"))
if not isinstance(previous, dict):
raise ValueError("Existing settings must be an object")
if encode(previous) == encode(settings):
return False
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent, delete=False) as handle:
temporary = Path(handle.name)
handle.write(payload)
os.replace(temporary, target)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
return True
if __name__ == "__main__":
print("Changed:", write_config("settings.json", {"workers":4,"owner":"Zoë"}))
Only a complete staged document replaces the target. The no-op branch avoids unnecessary writes, and the cleanup path preserves the original when committing fails.