03 / RELIABLE ADMINISTRATION TOOLS · LESSON 10

Preview configuration changes

Separate a proposed change from its application and preserve unrelated settings.

15 min · learn at your pace

Make the default action informative

A reusable administration function should make its effect inspectable. Here, update_config reads a JSON configuration and returns a change plan. It writes only when the caller explicitly passes apply=True. A preview and an application use the same comparison rules, so the preview explains what the file operation will do.

Keep unrelated settings. Replacing the entire object with a small changes dictionary could remove an owner label or a connection setting the caller never intended to touch. Merge the requested keys into a copy of the current configuration.

Equality needs a documented meaning

Python considers False == 0 and True == 1. JSON configuration often needs those values to remain different. Compare canonical JSON encodings: sort object keys and reject non-finite numbers. Under this lesson's rule, 1 and 1.0 also differ because their encodings differ. List order remains meaningful.

Use an explicit missing field in each proposed change. A missing key and a key whose value is null both produce None through dict.get, but they are different states. Sort changes by key for a stable review.

This lesson writes a virtual file, not a running service's configuration. The next lesson improves the file commit itself so a failed replacement cannot destroy the previous configuration.

Try an example.py
import json
print(False == 0)
print(json.dumps(False) == json.dumps(0))
YOUR TURN

Put it into practice.

Define update_config(path, changes, apply=False). Read an existing UTF-8 JSON object; require changes to be an object, otherwise raise ValueError. Reject non-finite JSON values. Compare values using JSON encoding with sorted keys, preserving numeric type distinctions. Return {changes: [...], applied: bool}; each changed key has key,missing,before,after, sorted by key. A missing before value is None. Preview never writes. apply=True merges changes, preserves unrelated keys, writes only if something differs, and sets applied True only for that write. Missing files and malformed JSON fail clearly.

See an explained solution
One way to solve it.py
import json
from pathlib import Path

def update_config(path, changes, apply=False):
    current = json.loads(Path(path).read_text(encoding="utf-8"))
    if not isinstance(current, dict) or not isinstance(changes, dict):
        raise ValueError("Configuration and changes must be objects")
    encode = lambda value: json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False)
    encode(current)
    encode(changes)
    plan = []
    for key in sorted(changes):
        missing = key not in current
        if missing or encode(current[key]) != encode(changes[key]):
            plan.append({"key": key, "missing": missing, "before": current.get(key), "after": changes[key]})
    if apply and plan:
        Path(path).write_text(encode(dict(current, **changes)) + "\n", encoding="utf-8")
    return {"changes": plan, "applied": bool(apply and plan)}

if __name__ == "__main__":
    print(update_config("settings.json", {"workers":4}))

The plan records exactly what differs, including type changes and missing keys. Preview leaves the file byte-for-byte intact, while application preserves keys outside the request.