Skip to content
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

More informative error for passing a list to dataset.transpose #7120

Merged
merged 9 commits into from
Oct 4, 2022
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"'{x}', " if isinstance(x, str) else f"{x}, " for x in dims[0]]
patrick-naylor marked this conversation as resolved.
Show resolved Hide resolved
raise TypeError(
f'transpose requires dims to be of hashable type. Expected "{"".join(list_fix)[:-2]}". Received "{dims[0]}" instead'
patrick-naylor marked this conversation as resolved.
Show resolved Hide resolved
)

# Use infix_dims to check once for missing dimensions
if len(dims) != 0:
_ = list(infix_dims(dims, self.dims, missing_dims))
Expand Down
11 changes: 11 additions & 0 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6806,3 +6806,14 @@ def test_string_keys_typing() -> None:
ds = xr.Dataset(dict(x=da))
mapping = {"y": da}
ds.assign(variables=mapping)


def test_traspose_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=r"transpose requires dims to be of hashable type.*"
):
ds.transpose(["y", "x"])