Skip to content

Commit 3d1a839

Browse files
authored
fix: zero default scalar for bytes fields in structured dtypes (#4495)
* fix: zero default scalar for bytes fields in structured dtypes * docs: name changelog entry after #4495
1 parent 246fa20 commit 3d1a839

3 files changed

Lines changed: 11 additions & 1 deletion

File tree

‎changes/4495.bugfix.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Structured data types now default byte-string (`S`) and raw-bytes (`V`) fields to zero bytes. Before, an array with a raw-bytes field failed to create without an explicit fill value, and byte-string fields defaulted to `b"0"`.

‎src/zarr/core/dtype/npy/structured.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,7 @@ def default_scalar(self) -> np.void:
579579
# zero count is representable by viewing the integer storage.
580580
value = np.zeros(1, dtype=dtype.byteorder + "i8").view(dtype)[0]
581581
else:
582-
value = np.array([0], dtype=dtype)[0]
582+
value = np.zeros(1, dtype=dtype)[0]
583583
values.append(value)
584584
return self._cast_scalar_unchecked(tuple(values))
585585

‎tests/test_dtype/test_npy/test_structured.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,3 +392,12 @@ def test_subarray_structured_dtype_raises() -> None:
392392
dtype = np.dtype([("f0", "i4", (2,))])
393393
with pytest.raises(ValueError, match="field 'f0' is a subarray"):
394394
Struct.from_native_dtype(dtype)
395+
396+
397+
@pytest.mark.parametrize("field_dtype", ["S4", "V4"])
398+
def test_default_scalar_bytes_field_is_zero(field_dtype: str) -> None:
399+
"""
400+
The default scalar of a bytes field is zero bytes, as for the same dtype outside a struct.
401+
"""
402+
dtype = np.dtype([("a", field_dtype), ("b", "<f4")])
403+
assert Struct.from_native_dtype(dtype).default_scalar().tobytes() == bytes(dtype.itemsize)

0 commit comments

Comments
 (0)