Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cast numpy scalars to arrays in as_compatible_data #9403

Merged
merged 11 commits into from
Sep 23, 2024
2 changes: 1 addition & 1 deletion xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ def as_compatible_data(
else:
data = np.asarray(data)

if not isinstance(data, np.ndarray) and (
if not isinstance(data, np.ndarray | np.generic) and (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is worth adding a comment, noting that we want to cast numpy scalars to arrays.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the latest commit does that, but please check if that's clear enough

hasattr(data, "__array_function__") or hasattr(data, "__array_namespace__")
):
return cast("T_DuckArray", data)
Expand Down
9 changes: 7 additions & 2 deletions xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2584,10 +2584,15 @@ def test_unchanged_types(self):
assert source_ndarray(x) is source_ndarray(as_compatible_data(x))

def test_converted_types(self):
for input_array in [[[0, 1, 2]], pd.DataFrame([[0, 1, 2]])]:
for input_array in [
[[0, 1, 2]],
pd.DataFrame([[0, 1, 2]]),
np.float64(1.4),
np.str_("abc"),
]:
actual = as_compatible_data(input_array)
assert_array_equal(np.asarray(input_array), actual)
assert np.ndarray == type(actual)
assert isinstance(actual, np.ndarray)
keewis marked this conversation as resolved.
Show resolved Hide resolved
assert np.asarray(input_array).dtype == actual.dtype

def test_masked_array(self):
Expand Down
Loading