Skip to content

Commit

Permalink
More informative error for passing a list to dataset.transpose (#7120)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
patrick-naylor and max-sixty authored Oct 4, 2022
1 parent 58ab594 commit 13c52b2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
3 changes: 2 additions & 1 deletion doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/patrick-naylor>`_

Documentation
~~~~~~~~~~~~~
Expand Down
7 changes: 7 additions & 0 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
15 changes: 15 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import pickle
import re
import sys
import warnings
from copy import copy, deepcopy
Expand Down Expand Up @@ -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

0 comments on commit 13c52b2

Please sign in to comment.