diff --git a/src/ufoLib2/serde/json.py b/src/ufoLib2/serde/json.py index b6e27565..9a99e0a1 100644 --- a/src/ufoLib2/serde/json.py +++ b/src/ufoLib2/serde/json.py @@ -1,17 +1,18 @@ from __future__ import annotations -from typing import Any, Type, cast +import json +from typing import Any, Type from ufoLib2.converters import structure, unstructure from ufoLib2.typing import T have_orjson = False try: - import orjson as json # type: ignore + import orjson have_orjson = True except ImportError: - import json # type: ignore + pass def dumps( @@ -26,18 +27,21 @@ def dumps( if indent is not None: if indent != 2: raise ValueError("indent must be 2 or None for orjson") - kwargs["option"] = kwargs.pop("option", 0) | json.OPT_INDENT_2 + kwargs["option"] = kwargs.pop("option", 0) | orjson.OPT_INDENT_2 if sort_keys: - kwargs["option"] = kwargs.pop("option", 0) | json.OPT_SORT_KEYS + kwargs["option"] = kwargs.pop("option", 0) | orjson.OPT_SORT_KEYS # orjson.dumps always returns bytes - result = json.dumps(data, **kwargs) + result = orjson.dumps(data, **kwargs) else: # built-in json.dumps returns a string, not bytes, hence the encoding s = json.dumps(data, indent=indent, sort_keys=sort_keys, **kwargs) result = s.encode("utf-8") - return cast(bytes, result) + return result def loads(s: str | bytes, object_class: Type[T], **kwargs: Any) -> T: - data = json.loads(s, **kwargs) + if have_orjson: + data = orjson.loads(s, **kwargs) + else: + data = json.loads(s, **kwargs) return structure(data, object_class) diff --git a/tests/serde/test_json.py b/tests/serde/test_json.py index 954d86cf..67cdab8b 100644 --- a/tests/serde/test_json.py +++ b/tests/serde/test_json.py @@ -20,7 +20,6 @@ def test_dumps_loads( ) -> None: if not have_orjson: monkeypatch.setattr(ufoLib2.serde.json, "have_orjson", have_orjson) - monkeypatch.setattr(ufoLib2.serde.json, "json", json) font = ufo_UbuTestData data = font.json_dumps() # type: ignore @@ -52,7 +51,6 @@ def test_dump_load( ) -> None: if not have_orjson: monkeypatch.setattr(ufoLib2.serde.json, "have_orjson", have_orjson) - monkeypatch.setattr(ufoLib2.serde.json, "json", json) font = ufo_UbuTestData with open(tmp_path / "test.json", "wb") as f: diff --git a/tox.ini b/tox.ini index 8d418c3e..e55a83b3 100644 --- a/tox.ini +++ b/tox.ini @@ -28,8 +28,6 @@ deps = commands = black --check --diff . isort --skip-gitignore --check-only --diff src tests - # typing stubs for orjson exist but I don't want mypy to use them! - pip uninstall -y orjson mypy --strict src tests flake8