Skip to content

Fix: coerce unknown types to O dtype #10339

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions xarray/compat/array_api_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,18 @@ def _future_array_api_result_type(*arrays_and_dtypes, xp):


def result_type(*arrays_and_dtypes, xp) -> np.dtype:
if xp is np or any(
isinstance(getattr(t, "dtype", t), np.dtype) for t in arrays_and_dtypes
):
return xp.result_type(*arrays_and_dtypes)
is_np_dtype = [
hasattr(t, "dtype") and isinstance(t.dtype, np.dtype) for t in arrays_and_dtypes
]
if xp is np or any(is_np_dtype):
# Numpy can only apply type promotion rules on non-builtin & numpy-compatible Python objects.
# So we convert any incompatible objects (e.g. user-defined class instances) stored in the array to numpy Object dtype.
# Then, numpy's type promotion will fall back to Object dtype rather than raising an exception.
all_valid_arrays_and_dtypes = [
t if is_np_dtype[i] or t.__class__.__module__ == "builtins" else np.object_
for i, t in enumerate(arrays_and_dtypes)
]
return xp.result_type(*all_valid_arrays_and_dtypes)
else:
return _future_array_api_result_type(*arrays_and_dtypes, xp=xp)

Expand Down
4 changes: 4 additions & 0 deletions xarray/tests/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ class DummyArrayAPINamespace:
([np.dtype("<U2"), str], np.dtype("U")),
([np.dtype("S3"), np.bytes_], np.dtype("S")),
([np.dtype("S10"), bytes], np.dtype("S")),
([type("Foo", (object,), {"foo": "bar"})()], np.object_),
([np.float32, type("Foo", (object,), {"foo": "bar"})()], np.object_),
([np.str_, type("Foo", (object,), {"foo": "bar"})()], np.object_),
([np.bytes_, type("Foo", (object,), {"foo": "bar"})()], np.object_),
],
)
def test_result_type(args, expected) -> None:
Expand Down
Loading