Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ New Features
- Support lazy grouping by dask arrays, and allow specifying ordered groups with ``UniqueGrouper(labels=["a", "b", "c"])``
(:issue:`2852`, :issue:`757`).
By `Deepak Cherian <https://github.com/dcherian>`_.
- Allow wrapping ``np.ndarray`` subclasses, e.g. ``astropy.units.Quantity`` (:issue:`9704`, :pull:`9760`).
By `Sam Levang <https://github.com/slevang>`_ and `Tien Vo <https://github.com/tien-vo>`_.

Breaking changes
~~~~~~~~~~~~~~~~
Expand Down
9 changes: 7 additions & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,13 @@ def convert_non_numpy_type(data):
else:
data = np.asarray(data)

# immediately return array-like types except `numpy.ndarray` subclasses and `numpy` scalars
if not isinstance(data, np.ndarray | np.generic) and (
if isinstance(data, np.matrix):
data = np.asarray(data)

# immediately return array-like types except `numpy.ndarray` and `numpy` scalars
# compare types with `is` instead of `isinstance` to allow `numpy.ndarray` subclasses
is_numpy = type(data) is np.ndarray or isinstance(data, np.generic)
if not is_numpy and (
hasattr(data, "__array_function__") or hasattr(data, "__array_namespace__")
):
return cast("T_DuckArray", data)
Expand Down
13 changes: 13 additions & 0 deletions xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2746,6 +2746,19 @@ def test_ones_like(self) -> None:
assert_identical(ones_like(orig), full_like(orig, 1))
assert_identical(ones_like(orig, dtype=int), full_like(orig, 1, dtype=int))

def test_numpy_ndarray_subclass(self):
class SubclassedArray(np.ndarray):
def __new__(cls, array, foo):
obj = np.asarray(array).view(cls)
obj.foo = foo
return obj

data = SubclassedArray([1, 2, 3], foo="bar")
actual = as_compatible_data(data)
assert isinstance(actual, SubclassedArray)
assert actual.foo == "bar"
assert_array_equal(data, actual)

def test_unsupported_type(self):
# Non indexable type
class CustomArray(NDArrayMixin):
Expand Down
Loading