Bidirectional, JSON-patch-compliant diffs between Python data structures.
📖 Documentation | Quick Start | API Reference
Patchdiff diffs composite structures of dicts, lists, sets and tuples, and gives you both directions in one call: the patches to get from input to output, and the patches to get back. Patches are RFC 6902 JSON-patch style, serializable to JSON, and can be applied in place or to a copy, which makes undo/redo, change synchronization and state auditing one-liners.
frompatchdiffimportapply, diff, iapply, to_jsoninput= {"a": [5, 7, 9, {"a", "b", "c"}], "b": 6}
output= {"a": [5, 2, 9, {"b", "c"}], "b": 6, "c": 7}
ops, reverse_ops=diff(input, output)
assertapply(input, ops) ==output# patch a copy...assertapply(output, reverse_ops) ==input# ...and it round-tripsiapply(input, ops) # or patch in placeassertinput==outputprint(to_json(ops, indent=4))When your own code makes the changes, produce() (inspired by Immer) skips the comparison entirely: it hands your recipe a draft, records every mutation, and returns the result plus both patch directions. Cost scales with the number of mutations instead of the size of the state:
frompatchdiffimportproducebase= {"count": 0, "items": [1, 2, 3]}
defrecipe(draft):
draft["count"] =5draft["items"].append(4)
result, patches, reverse_patches=produce(base, recipe)
assertbase== {"count": 0, "items": [1, 2, 3]} # base is untouchedassertresult== {"count": 5, "items": [1, 2, 3, 4]}With in_place=True, mutations (and patches applied with iapply) write straight through proxy-backed state, the natural companion to observ reactive objects, where mutating through the proxy is what triggers watchers. See Observ Integration for reactive state with undo/redo.
pip install patchdiff # or: uv add patchdiffNo dependencies, Python >= 3.13.
The documentation covers diffing semantics, applying patches, JSON pointers, proxy-based patch generation, serialization and the gotchas, plus the internals for the curious.