Skip to content

Commit 6645433

Browse files
committed
fix: allow for intlike strings in json parsing
1 parent 48e7f4d commit 6645433

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/zarr/core/dtype/npy/common.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@
5858
IntishFloat = NewType("IntishFloat", float)
5959
"""A type for floats that represent integers, like 1.0 (but not 1.1)."""
6060

61+
IntishStr = NewType("IntishStr", str)
62+
"""A type for strings that represent integers, like "0" or "42"."""
63+
6164
NumpyEndiannessStr = Literal[">", "<", "="]
6265
NUMPY_ENDIANNESS_STR: Final = ">", "<", "="
6366

@@ -488,6 +491,31 @@ def check_json_intish_float(data: JSON) -> TypeGuard[IntishFloat]:
488491
return isinstance(data, float) and data.is_integer()
489492

490493

494+
def check_json_intish_str(data: JSON) -> TypeGuard[IntishStr]:
495+
"""
496+
Check if a JSON value is a string that represents an integer, like "0", "42", or "-5".
497+
498+
Parameters
499+
----------
500+
data : JSON
501+
The JSON value to check.
502+
503+
Returns
504+
-------
505+
bool
506+
True if the data is a string representing an integer, False otherwise.
507+
"""
508+
if not isinstance(data, str):
509+
return False
510+
511+
try:
512+
int(data)
513+
except ValueError:
514+
return False
515+
else:
516+
return True
517+
518+
491519
def check_json_str(data: JSON) -> TypeGuard[str]:
492520
"""
493521
Check if a JSON value is a string.

src/zarr/core/dtype/npy/int.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from zarr.core.dtype.npy.common import (
2727
check_json_int,
2828
check_json_intish_float,
29+
check_json_intish_str,
2930
endianness_to_numpy_str,
3031
get_endianness_from_numpy_dtype,
3132
)
@@ -209,6 +210,10 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TIntScalar
209210
return self._cast_scalar_unchecked(data)
210211
if check_json_intish_float(data):
211212
return self._cast_scalar_unchecked(int(data))
213+
214+
if check_json_intish_str(data):
215+
return self._cast_scalar_unchecked(int(data))
216+
212217
raise TypeError(f"Invalid type: {data}. Expected an integer.")
213218

214219
def to_json_scalar(self, data: object, *, zarr_format: ZarrFormat) -> int:

0 commit comments

Comments
 (0)