Skip to content

Commit f700dd8

Browse files
TomNicholassnowman2
authored andcommitted
Dataset.__setitem__ raise on being passed a Dataset (for single key) (pydata#5839)
* raise on being passed a Dataset * linting * added a test * whatsnew * linting * clearer grammar in error message
1 parent 71d4b7c commit f700dd8

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

doc/whats-new.rst

+3
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,9 @@ Documentation
8686

8787
- Users are instructed to try ``use_cftime=True`` if a ``TypeError`` occurs when combining datasets and one of the types involved is a subclass of ``cftime.datetime`` (:pull:`5776`).
8888
By `Zeb Nicholls <https://github.com/znicholls>`_.
89+
- A clearer error is now raised if a user attempts to assign a Dataset to a single key of
90+
another Dataset. (:pull:`5839`)
91+
By `Tom Nicholas <https://github.com/TomNicholas>`_.
8992

9093
Internal Changes
9194
~~~~~~~~~~~~~~~~

xarray/core/dataset.py

+5
Original file line numberDiff line numberDiff line change
@@ -1557,6 +1557,11 @@ def __setitem__(self, key: Union[Hashable, List[Hashable], Mapping], value) -> N
15571557
self.update(dict(zip(key, value)))
15581558

15591559
else:
1560+
if isinstance(value, Dataset):
1561+
raise TypeError(
1562+
"Cannot assign a Dataset to a single key - only a DataArray or Variable object can be stored under"
1563+
"a single key."
1564+
)
15601565
self.update({key: value})
15611566

15621567
def _setitem_check(self, key, value):

xarray/tests/test_dataset.py

+3
Original file line numberDiff line numberDiff line change
@@ -3395,6 +3395,9 @@ def test_setitem(self):
33953395
# override an existing value
33963396
data1["A"] = 3 * data2["A"]
33973397
assert_equal(data1["A"], 3 * data2["A"])
3398+
# can't assign a dataset to a single key
3399+
with pytest.raises(TypeError, match="Cannot assign a Dataset to a single key"):
3400+
data1["D"] = xr.Dataset()
33983401

33993402
# test assignment with positional and label-based indexing
34003403
data3 = data1[["var1", "var2"]]

0 commit comments

Comments
 (0)