Skip to content

Fix issue tuple as dimension #5477

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1381,9 +1381,14 @@ def _construct_dataarray(self, name: Hashable) -> "DataArray":
try:
variable = self._variables[name]
except KeyError:
_, name, variable = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)
if isinstance(name, tuple):
raise KeyError(
"The dimension provided is a tuple, you may intended to pass a list"
)
else:
_, name, variable = _get_virtual_variable(
self._variables, name, self._level_coords, self.dims
)

needed_dims = set(variable.dims)

Expand Down Expand Up @@ -5983,10 +5988,11 @@ def sortby(self, variables, ascending=True):
"""
from .dataarray import DataArray

if not isinstance(variables, list):
if not isinstance(variables, (list, tuple)):
variables = [variables]
else:
variables = variables

variables = [v if isinstance(v, DataArray) else self[v] for v in variables]
aligned_vars = align(self, *variables, join="left")
aligned_self = aligned_vars[0]
Expand Down
5 changes: 5 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4429,6 +4429,11 @@ def test_sortby(self):
actual = da.sortby(["x", "y"])
assert_equal(actual, expected)

# test not throwing an error if sorted with tuple
expected = sorted2d
actual = da.sortby(da.dims)
assert_equal(actual, expected)

@requires_bottleneck
def test_rank(self):
# floats
Expand Down
7 changes: 5 additions & 2 deletions xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -3296,13 +3296,16 @@ def test_getitem(self):
expected = data.isel(dim1=0)
assert_identical(expected, actual)

def test_getitem_hashable(self):
def test_error_tuple(self):
data = create_test_data()
data[(3, 4)] = data["var1"] + 1
expected = data["var1"] + 1
expected.name = (3, 4)
assert_identical(expected, data[(3, 4)])
with pytest.raises(KeyError, match=r"('var1', 'var2')"):
with pytest.raises(
KeyError,
match="The dimension provided is a tuple, you may intended to pass a list",
):
data[("var1", "var2")]

def test_virtual_variables_default_coords(self):
Expand Down