Skip to content

Commit 13c52b2

Browse files
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 <[email protected]> * 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 <[email protected]>
1 parent 58ab594 commit 13c52b2

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

doc/whats-new.rst

+2-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ Deprecations
3333

3434
Bug fixes
3535
~~~~~~~~~
36-
36+
- Fixed :py:meth:`Dataset.transpose` to raise a more informative error. (:issue:`6502`, :pull:`7120`)
37+
By `Patrick Naylor <https://github.com/patrick-naylor>`_
3738

3839
Documentation
3940
~~~~~~~~~~~~~

xarray/core/dataset.py

+7
Original file line numberDiff line numberDiff line change
@@ -5401,6 +5401,13 @@ def transpose(
54015401
numpy.transpose
54025402
DataArray.transpose
54035403
"""
5404+
# Raise error if list is passed as dims
5405+
if (len(dims) > 0) and (isinstance(dims[0], list)):
5406+
list_fix = [f"{repr(x)}" if isinstance(x, str) else f"{x}" for x in dims[0]]
5407+
raise TypeError(
5408+
f'transpose requires dims to be passed as multiple arguments. Expected `{", ".join(list_fix)}`. Received `{dims[0]}` instead'
5409+
)
5410+
54045411
# Use infix_dims to check once for missing dimensions
54055412
if len(dims) != 0:
54065413
_ = list(infix_dims(dims, self.dims, missing_dims))

xarray/tests/test_dataset.py

+15
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import pickle
4+
import re
45
import sys
56
import warnings
67
from copy import copy, deepcopy
@@ -6806,3 +6807,17 @@ def test_string_keys_typing() -> None:
68066807
ds = xr.Dataset(dict(x=da))
68076808
mapping = {"y": da}
68086809
ds.assign(variables=mapping)
6810+
6811+
6812+
def test_transpose_error() -> None:
6813+
# Transpose dataset with list as argument
6814+
# Should raise error
6815+
ds = xr.Dataset({"foo": (("x", "y"), [[21]]), "bar": (("x", "y"), [[12]])})
6816+
6817+
with pytest.raises(
6818+
TypeError,
6819+
match=re.escape(
6820+
"transpose requires dims to be passed as multiple arguments. Expected `'y', 'x'`. Received `['y', 'x']` instead"
6821+
),
6822+
):
6823+
ds.transpose(["y", "x"]) # type: ignore

0 commit comments

Comments
 (0)