Skip to content

fix: BaseFloat._check_scalar rejects invalid string values (#3586)#3762

Merged
d-v-b merged 2 commits intozarr-developers:mainfrom
abishop1990:fix/basefloat-check-scalar-3586
Mar 11, 2026
Merged

fix: BaseFloat._check_scalar rejects invalid string values (#3586)#3762
d-v-b merged 2 commits intozarr-developers:mainfrom
abishop1990:fix/basefloat-check-scalar-3586

Conversation

@abishop1990
Copy link
Contributor

Summary

Fixes #3586.

BaseFloat._check_scalar returned True for all strings because FloatLike includes str. This caused invalid strings like 'not valid' to pass the scalar check, then raise a confusing ValueError in _cast_scalar_unchecked instead of the expected TypeError.

Root Cause

FloatLike = SupportsIndex | SupportsFloat | bytes | str, so isinstance('not valid', FloatLike) is True. When _cast_scalar_unchecked calls np.float32('not valid') it raises ValueError, not TypeError.

Changes

BaseFloat._check_scalar now validates string inputs by attempting conversion:

  • Valid float strings ('NaN', 'inf', '-inf') → returns True (existing behaviour preserved)
  • Invalid strings ('not valid', etc.) → returns False, causing cast_scalar to raise TypeError

Testing

Added invalid string test cases to invalid_scalar_params for Float16, Float32, and Float64.

tests/test_dtype/test_npy/test_float.py  83 passed

…lopers#3586)

BaseFloat._check_scalar returned True for all strings because the
FloatLike type union includes str. This allowed invalid strings like
'not valid' to pass the check and then raise a confusing ValueError
in _cast_scalar_unchecked instead of the expected TypeError.

Fix _check_scalar to validate string inputs by attempting conversion:
- Valid float strings (e.g. 'NaN', 'inf', '-inf', '1.5') return True
- Invalid strings (e.g. 'not valid') return False, causing cast_scalar
  to raise TypeError as expected

Add test cases for invalid string inputs to invalid_scalar_params.

Fixes zarr-developers#3586
@d-v-b d-v-b merged commit fa61ed8 into zarr-developers:main Mar 11, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BaseFloat._check_scalar does not properly check string values

2 participants