quantlab.utils.atomic.write_json_atomically#

quantlab.utils.atomic.write_json_atomically(path, payload, **json_kwargs)[source]#

Serialise payload as JSON to path with an atomic replace.

Missing parent directories are created. json_kwargs is forwarded unchanged to json.dump, so each caller keeps its own formatting (compact, indent=2, sort_keys=True and so on).

On any exception, including KeyboardInterrupt, the temporary file is removed and the exception propagates, leaving the previous file (if any) untouched.

Parameters:
pathstr | Path

Destination file.

payloadobject

Any object json.dump accepts.

**json_kwargs

Formatting options passed to json.dump.

Examples

>>> write_json_atomically("run/watermark.json", {"last": "2024-01-31"})
>>> write_json_atomically("run/manifest.json", data, indent=2, sort_keys=True)