Skip to content

Commit cfe3f2b

Browse files
committed
floatish strings
1 parent 6645433 commit cfe3f2b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@
6161
IntishStr = NewType("IntishStr", str)
6262
"""A type for strings that represent integers, like "0" or "42"."""
6363

64+
FloatishStr = NewType("FloatishStr", str)
65+
"""A type for strings that represent floats, like "3.14" or "-2.5"."""
66+
6467
NumpyEndiannessStr = Literal[">", "<", "="]
6568
NUMPY_ENDIANNESS_STR: Final = ">", "<", "="
6669

@@ -516,6 +519,34 @@ def check_json_intish_str(data: JSON) -> TypeGuard[IntishStr]:
516519
return True
517520

518521

522+
def check_json_floatish_str(data: JSON) -> TypeGuard[FloatishStr]:
523+
"""
524+
Check if a JSON value is a string that represents a float, like "3.14", "-2.5", or "0.0".
525+
526+
Note: This function is intended to be used AFTER check_json_float_v2/v3, so it only
527+
handles regular string representations that those functions don't cover.
528+
529+
Parameters
530+
----------
531+
data : JSON
532+
The JSON value to check.
533+
534+
Returns
535+
-------
536+
bool
537+
True if the data is a string representing a regular float, False otherwise.
538+
"""
539+
if not isinstance(data, str):
540+
return False
541+
542+
try:
543+
float(data)
544+
except ValueError:
545+
return False
546+
else:
547+
return True
548+
549+
519550
def check_json_str(data: JSON) -> TypeGuard[str]:
520551
"""
521552
Check if a JSON value is a string.

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
TFloatScalar_co,
2020
check_json_float_v2,
2121
check_json_float_v3,
22+
check_json_floatish_str,
2223
endianness_to_numpy_str,
2324
float_from_json_v2,
2425
float_from_json_v3,
@@ -270,13 +271,17 @@ def from_json_scalar(self, data: JSON, *, zarr_format: ZarrFormat) -> TFloatScal
270271
if zarr_format == 2:
271272
if check_json_float_v2(data):
272273
return self._cast_scalar_unchecked(float_from_json_v2(data))
274+
elif check_json_floatish_str(data):
275+
return self._cast_scalar_unchecked(float(data))
273276
else:
274277
raise TypeError(
275278
f"Invalid type: {data}. Expected a float or a special string encoding of a float."
276279
)
277280
elif zarr_format == 3:
278281
if check_json_float_v3(data):
279282
return self._cast_scalar_unchecked(float_from_json_v3(data))
283+
elif check_json_floatish_str(data):
284+
return self._cast_scalar_unchecked(float(data))
280285
else:
281286
raise TypeError(
282287
f"Invalid type: {data}. Expected a float or a special string encoding of a float."

0 commit comments

Comments
 (0)