Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(py): Hugr.to_json and .load_json helpers #1403

Merged
merged 3 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ repos:
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.9.0
rev: v1.11.0
hooks:
- id: mypy
additional_dependencies: [pydantic]
Expand Down
12 changes: 12 additions & 0 deletions hugr-py/src/hugr/hugr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import json
from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass, field, replace
from typing import (
Expand Down Expand Up @@ -623,3 +624,14 @@ def from_serial(cls, serial: SerialHugr) -> Hugr:
)

return hugr

def to_json(self) -> str:
"""Serialize the HUGR to a JSON string."""
return self.to_serial().to_json()

@classmethod
def load_json(cls, json_str: str) -> Hugr:
"""Deserialize a JSON string into a HUGR."""
json_dict = json.loads(json_str)
serial = SerialHugr.load_json(json_dict)
return cls.from_serial(serial)
2 changes: 1 addition & 1 deletion hugr-py/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from typing_extensions import Self

from hugr import tys
import hugr.tys as tys
from hugr.hugr import Hugr
from hugr.ops import AsCustomOp, Command, Custom, DataflowOp
from hugr.serialization.serial_hugr import SerialHugr
Expand Down
14 changes: 13 additions & 1 deletion hugr-py/tests/test_hugr_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import pytest

from hugr import ops, tys, val
import hugr.ops as ops
import hugr.tys as tys
import hugr.val as val
from hugr.dfg import Dfg, _ancestral_sibling
from hugr.function import Module
from hugr.hugr import Hugr
Expand Down Expand Up @@ -67,6 +69,16 @@ def test_simple_id():
validate(simple_id().hugr)


def test_json_roundtrip():
hugr = simple_id().hugr
json = hugr.to_json()

hugr2 = Hugr.load_json(json)
json2 = hugr2.to_json()

assert json2 == json


def test_multiport():
h = Dfg(tys.Bool)
(a,) = h.inputs()
Expand Down
Loading