diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 24ff240cea3..c22b252728f 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -51,6 +51,9 @@ Bug fixes - Fixed labeled indexing with slice bounds given by xarray objects with datetime64 or timedelta64 dtypes (:issue:`1240`). By `Stephan Hoyer `_. +- Attempting to convert an xarray.Dataset into a numpy array now raises an + informative error message. + By `Stephan Hoyer `_. - Fixed a bug in decode_cf_datetime where ``int32`` arrays weren't parsed correctly (:issue:`2002`). By `Fabien Maussion `_. diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index e960d433f98..f28e7980b34 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -849,6 +849,12 @@ def __iter__(self): FutureWarning, stacklevel=2) return iter(self._variables) + def __array__(self, dtype=None): + raise TypeError('cannot directly convert an xarray.Dataset into a ' + 'numpy array. Instead, create an xarray.DataArray ' + 'first, either with indexing on the Dataset or by ' + 'invoking the `to_array()` method.') + @property def nbytes(self): return sum(v.nbytes for v in self.variables.values()) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index b4ca14d2384..826f50003fa 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -443,6 +443,11 @@ def test_properties(self): assert Dataset({'x': np.int64(1), 'y': np.float32([1, 2])}).nbytes == 16 + def test_asarray(self): + ds = Dataset({'x': 0}) + with raises_regex(TypeError, 'cannot directly convert'): + np.asarray(ds) + def test_get_index(self): ds = Dataset({'foo': (('x', 'y'), np.zeros((2, 3)))}, coords={'x': ['a', 'b']})