Skip to content

Raise an informative error message when converting Dataset -> np.ndarray #2032

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

Merged
merged 2 commits into from
Apr 3, 2018
Merged
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
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/shoyer>`_.
- Attempting to convert an xarray.Dataset into a numpy array now raises an
informative error message.
By `Stephan Hoyer <https://github.com/shoyer>`_.
- Fixed a bug in decode_cf_datetime where ``int32`` arrays weren't parsed
correctly (:issue:`2002`).
By `Fabien Maussion <https://github.com/fmaussion>`_.
Expand Down
6 changes: 6 additions & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']})
Expand Down