Skip to content

Commit

Permalink
feat(py): Hugr.to_json and .load_json helpers (#1403)
Browse files Browse the repository at this point in the history
drive-by: For some reason mypy started complaining about some unrelated
imports, this includes a fix -.-'
  • Loading branch information
aborgna-q committed Aug 12, 2024
1 parent aa81c9a commit e7f9f4c
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 3 deletions.
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

0 comments on commit e7f9f4c

Please sign in to comment.