Skip to content

Commit 39219fa

Browse files
committed
truncate U and S scalars in _cast_value_unsafe
1 parent 7806563 commit 39219fa

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

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

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,15 @@ def check_value(self, data: object) -> bool:
8686
# this is generous for backwards compatibility
8787
return isinstance(data, np.bytes_ | str | bytes | int)
8888

89-
def _cast_value_unsafe(self, value: object) -> np.bytes_:
90-
return self.to_dtype().type(value)
89+
def _cast_value_unsafe(self, data: object) -> np.bytes_:
90+
# We explicitly truncate the result because of the following numpy behavior:
91+
# >>> x = np.dtype('S3').type('hello world')
92+
# >>> x
93+
# np.bytes_(b'hello world')
94+
# >>> x.dtype
95+
# dtype('S11')
96+
97+
return self.to_dtype().type(data[: self.length]) # type: ignore[index]
9198

9299
@property
93100
def item_size(self) -> int:
@@ -168,7 +175,14 @@ def check_value(self, data: object) -> bool:
168175
return isinstance(data, str | np.str_ | bytes | int)
169176

170177
def _cast_value_unsafe(self, data: object) -> np.str_:
171-
return self.to_dtype().type(data)
178+
# We explicitly truncate the result because of the following numpy behavior:
179+
# >>> x = np.dtype('U3').type('hello world')
180+
# >>> x
181+
# np.str_('hello world')
182+
# >>> x.dtype
183+
# dtype('U11')
184+
185+
return self.to_dtype().type(data[: self.length]) # type: ignore[index]
172186

173187
@property
174188
def item_size(self) -> int:

0 commit comments

Comments
 (0)