Skip to content

Commit

Permalink
do use orjson typing stubs after all
Browse files Browse the repository at this point in the history
  • Loading branch information
anthrotype committed Nov 4, 2022
1 parent ebc3131 commit b88ff09
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 12 deletions.
20 changes: 12 additions & 8 deletions 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(
Expand All @@ -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)
2 changes: 0 additions & 2 deletions tests/serde/test_json.py
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 0 additions & 2 deletions tox.ini
Expand Up @@ -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

Expand Down

0 comments on commit b88ff09

Please sign in to comment.