Skip to content

Commit 49ae0f8

Browse files
authored
State which variables not present in drop vars error message (#7518)
* test * improve error message * whatsnew * order the names of missing variables before raising * escape regex so it matches
1 parent 6d771fc commit 49ae0f8

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ Deprecations
4545

4646
Bug fixes
4747
~~~~~~~~~
48+
49+
- Improve error message when using in :py:meth:`Dataset.drop_vars` to state which variables can't be dropped. (:pull:`7518`)
50+
By `Tom Nicholas <https://github.com/TomNicholas>`_.
4851
- Require to explicitly defining optional dimensions such as hue
4952
and markersize for scatter plots. (:issue:`7314`, :pull:`7277`).
5053
By `Jimmy Westling <https://github.com/illviljan>`_.

xarray/core/dataset.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5051,9 +5051,9 @@ def _assert_all_in_dataset(
50515051
if virtual_okay:
50525052
bad_names -= self.virtual_variables
50535053
if bad_names:
5054+
ordered_bad_names = [name for name in names if name in bad_names]
50545055
raise ValueError(
5055-
"One or more of the specified variables "
5056-
"cannot be found in this dataset"
5056+
f"These variables cannot be found in this dataset: {ordered_bad_names}"
50575057
)
50585058

50595059
def drop_vars(

xarray/tests/test_dataset.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2503,7 +2503,12 @@ def test_drop_variables(self) -> None:
25032503
actual = data.drop_vars(["time"])
25042504
assert_identical(expected, actual)
25052505

2506-
with pytest.raises(ValueError, match=r"cannot be found"):
2506+
with pytest.raises(
2507+
ValueError,
2508+
match=re.escape(
2509+
"These variables cannot be found in this dataset: ['not_found_here']"
2510+
),
2511+
):
25072512
data.drop_vars("not_found_here")
25082513

25092514
actual = data.drop_vars("not_found_here", errors="ignore")

0 commit comments

Comments
 (0)