Skip to content

Dataset.__setitem__ raise on being passed a Dataset (for single key) #5839

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 6 commits into from
Oct 23, 2021
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 @@ -80,6 +80,9 @@ Documentation

- 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`).
By `Zeb Nicholls <https://github.com/znicholls>`_.
- A clearer error is now raised if a user attempts to assign a Dataset to a single key of
another Dataset. (:pull:`5839`)
By `Tom Nicholas <https://github.com/TomNicholas>`_.

Internal Changes
~~~~~~~~~~~~~~~~
Expand Down
5 changes: 5 additions & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1557,6 +1557,11 @@ def __setitem__(self, key: Union[Hashable, List[Hashable], Mapping], value) -> N
self.update(dict(zip(key, value)))

else:
if isinstance(value, Dataset):
raise TypeError(
"Cannot assign a Dataset to a single key - only a DataArray or Variable object can be stored under"
"a single key."
)
self.update({key: value})

def _setitem_check(self, key, value):
Expand Down
3 changes: 3 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3395,6 +3395,9 @@ def test_setitem(self):
# override an existing value
data1["A"] = 3 * data2["A"]
assert_equal(data1["A"], 3 * data2["A"])
# can't assign a dataset to a single key
with pytest.raises(TypeError, match="Cannot assign a Dataset to a single key"):
data1["D"] = xr.Dataset()

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