From 13c52b27b777709fc3316cf4334157f50904c02b Mon Sep 17 00:00:00 2001 From: Patrick Naylor Date: Tue, 4 Oct 2022 11:22:52 -0700 Subject: [PATCH] More informative error for passing a list to dataset.transpose (#7120) * Added statement to check if list is passed for dims and raise a more helpful error * Fixed issue where isinstance would not work when no arguments are passed * Added test * Updated whats-new.rst * Updated whats-new.rst with pull number * Removed test print statement * Update xarray/core/dataset.py Co-authored-by: Maximilian Roos <5635139+max-sixty@users.noreply.github.com> * Fixed test to inclued whole error output and imported regex. Changed transpose join statement * Hopefully fixed typecheck error and improved readability from suggestions by @max-sixty Co-authored-by: Maximilian Roos <5635139+max-sixty@users.noreply.github.com> --- doc/whats-new.rst | 3 ++- xarray/core/dataset.py | 7 +++++++ xarray/tests/test_dataset.py | 15 +++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 2b809711792..b2045ec9b72 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -33,7 +33,8 @@ Deprecations Bug fixes ~~~~~~~~~ - +- Fixed :py:meth:`Dataset.transpose` to raise a more informative error. (:issue:`6502`, :pull:`7120`) + By `Patrick Naylor `_ Documentation ~~~~~~~~~~~~~ diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 03bead3f00a..1735fdf8482 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -5401,6 +5401,13 @@ def transpose( numpy.transpose DataArray.transpose """ + # Raise error if list is passed as dims + if (len(dims) > 0) and (isinstance(dims[0], list)): + list_fix = [f"{repr(x)}" if isinstance(x, str) else f"{x}" for x in dims[0]] + raise TypeError( + f'transpose requires dims to be passed as multiple arguments. Expected `{", ".join(list_fix)}`. Received `{dims[0]}` instead' + ) + # Use infix_dims to check once for missing dimensions if len(dims) != 0: _ = list(infix_dims(dims, self.dims, missing_dims)) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index e2d120914d7..6c7d474aee4 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -1,6 +1,7 @@ from __future__ import annotations import pickle +import re import sys import warnings from copy import copy, deepcopy @@ -6806,3 +6807,17 @@ def test_string_keys_typing() -> None: ds = xr.Dataset(dict(x=da)) mapping = {"y": da} ds.assign(variables=mapping) + + +def test_transpose_error() -> None: + # Transpose dataset with list as argument + # Should raise error + ds = xr.Dataset({"foo": (("x", "y"), [[21]]), "bar": (("x", "y"), [[12]])}) + + with pytest.raises( + TypeError, + match=re.escape( + "transpose requires dims to be passed as multiple arguments. Expected `'y', 'x'`. Received `['y', 'x']` instead" + ), + ): + ds.transpose(["y", "x"]) # type: ignore