MCPcopy Create free account
hub / github.com/Graphify-Labs/graphify / _write_graph_json_atomic

Function _write_graph_json_atomic

graphify/export.py:658–706  ·  view source on GitHub ↗

Byte-identical replacement for ``write_json_atomic(..., compact=True)``. ``json.dump(obj, f, separators=(",", ":"))`` cannot use the C encoder (the one-shot path is only taken by ``dumps``/``encode``), so a large graph pays the pure-Python iterator for every node and edge. Here the two

(output_path: str, data: dict)

Source from the content-addressed store, hash-verified

656
657
658def _write_graph_json_atomic(output_path: str, data: dict) -> None:
659 """Byte-identical replacement for ``write_json_atomic(..., compact=True)``.
660
661 ``json.dump(obj, f, separators=(",", ":"))`` cannot use the C encoder (the
662 one-shot path is only taken by ``dumps``/``encode``), so a large graph pays
663 the pure-Python iterator for every node and edge. Here the two item lists are
664 written with ``json.dumps`` per item, which is the same encoders
665 (``encode_basestring_ascii`` for ``ensure_ascii=True``), the same separators
666 and the same insertion order, so the file's bytes are unchanged.
667 """
668 from graphify.paths import _atomic_replace
669
670 def _dump_item(item: dict) -> str:
671 return json.dumps(item, ensure_ascii=True, separators=(",", ":"))
672
673 def _write_items(f, items: list[dict]) -> None:
674 f.write("[")
675 first = True
676 chunk: list[str] = []
677 for item in items:
678 chunk.append(_dump_item(item))
679 if len(chunk) >= _JSON_WRITE_CHUNK:
680 text = ",".join(chunk)
681 f.write(text if first else "," + text)
682 first = False
683 chunk.clear()
684 if chunk:
685 text = ",".join(chunk)
686 f.write(text if first else "," + text)
687 f.write("]")
688
689 def _write(f) -> None:
690 f.write("{")
691 first = True
692 for key, value in data.items():
693 if not first:
694 f.write(",")
695 first = False
696 f.write(json.dumps(key, ensure_ascii=True))
697 f.write(":")
698 if key == "nodes" and isinstance(value, list):
699 _write_items(f, value)
700 elif key == "links" and isinstance(value, list):
701 _write_items(f, value)
702 else:
703 f.write(json.dumps(value, ensure_ascii=True, separators=(",", ":")))
704 f.write("}")
705
706 _atomic_replace(output_path, _write)
707
708
709def prune_dangling_edges(graph_data: dict) -> tuple[dict, int]:

Callers 1

to_jsonFunction · 0.85

Calls 1

_atomic_replaceFunction · 0.90

Tested by

no test coverage detected