Skip to content

Add numpy encoder class for json.dumps #933

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

Merged
merged 6 commits into from
Apr 15, 2022
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
3 changes: 3 additions & 0 deletions docs/release.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ Bug fixes
value when empty chunks are read back in.
By :user:`Vyas Ramasubramani <vyasr>`; :issue:`965`.

* Add number encoder for ``json.dumps`` to support numpy intergers in
``chunks`` arguments. By :user:`Eric Prestat <ericpre>` :issue:`697`.

.. _release_2.11.1:

2.11.1
Expand Down
5 changes: 5 additions & 0 deletions zarr/tests/test_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -714,3 +714,8 @@ def test_create_read_only(zarr_version):
assert z.read_only
with pytest.raises(PermissionError):
z[:] = 42


def test_json_dumps_chunks_numpy_dtype():
z = zeros((10,), chunks=(np.int64(2),))
assert np.all(z[...] == 0)
14 changes: 12 additions & 2 deletions zarr/tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import numpy as np
import pytest

from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size, info_html_report,
info_text_report, is_total_slice, normalize_chunks,
from zarr.core import Array
from zarr.util import (all_equal, flatten, guess_chunks, human_readable_size,
info_html_report, info_text_report, is_total_slice,
json_dumps, normalize_chunks,
normalize_dimension_separator,
normalize_fill_value, normalize_order,
normalize_resize_args, normalize_shape, retry_call,
Expand Down Expand Up @@ -238,3 +240,11 @@ def test_all_equal():
# all_equal(None, *) always returns False
assert not all_equal(None, np.array([None, None]))
assert not all_equal(None, np.array([None, 10]))


def test_json_dumps_numpy_dtype():
assert json_dumps(np.int64(0)) == json_dumps(0)
assert json_dumps(np.float32(0)) == json_dumps(float(0))
# Check that we raise the error of the superclass for unsupported object
with pytest.raises(TypeError):
json_dumps(Array)
14 changes: 13 additions & 1 deletion zarr/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,22 @@ def flatten(arg: Iterable) -> Iterable:
}


class NumberEncoder(json.JSONEncoder):

def default(self, o):
# See json.JSONEncoder.default docstring for explanation
# This is necessary to encode numpy dtype
if isinstance(o, numbers.Integral):
return int(o)
if isinstance(o, numbers.Real):
return float(o)
return json.JSONEncoder.default(self, o)


def json_dumps(o: Any) -> bytes:
"""Write JSON in a consistent, human-readable way."""
return json.dumps(o, indent=4, sort_keys=True, ensure_ascii=True,
separators=(',', ': ')).encode('ascii')
separators=(',', ': '), cls=NumberEncoder).encode('ascii')


def json_loads(s: str) -> Dict[str, Any]:
Expand Down