Skip to content

Fix sortby raising KeyError when passed a tuple of dimension names#11297

Open
thodson-usgs wants to merge 1 commit intopydata:mainfrom
thodson-usgs:fix-sortby-tuple-4821
Open

Fix sortby raising KeyError when passed a tuple of dimension names#11297
thodson-usgs wants to merge 1 commit intopydata:mainfrom
thodson-usgs:fix-sortby-tuple-4821

Conversation

@thodson-usgs
Copy link
Copy Markdown

@thodson-usgs thodson-usgs commented Apr 13, 2026

Summary

  • Fixes da.sortby(da.dims) raising KeyError when da.dims is a tuple (e.g. ('x', 'y'))
  • Tuples are now treated as iterables of variable names, consistent with the str | Iterable[Hashable] convention established in dimensions: type as str | Iterable[Hashable]? #6142

Closes #4821

Usage example

>>> import xarray as xr
>>> da = xr.DataArray(
...     [[1, 2], [3, 4], [5, 6]],
...     coords={"x": ["c", "b", "a"], "y": [1, 0]},
... )
>>> da.sortby(da.dims)  # da.dims is the tuple ("x", "y")
<xarray.DataArray (x: 3, y: 2)> Size: 48B
array([[6, 5],
       [4, 3],
       [2, 1]])
Coordinates:
  * x        (x) <U1 12B 'a' 'b' 'c'
  * y        (y) int64 16B 0 1

Test plan

  • da.sortby(da.dims) works when da.dims is a tuple of dimension names
  • ds.sortby(("x", "y")) sorts by both dimensions
  • Existing sortby tests pass (string, list, DataArray, descending, NaN handling)
  • whats-new.rst entry added

[This is Claude Code on behalf of Timothy Hodson]

@thodson-usgs thodson-usgs force-pushed the fix-sortby-tuple-4821 branch 4 times, most recently from 419f4ac to 0de98c3 Compare April 15, 2026 13:36
Closes pydata#4821

Co-authored-by: Claude <noreply@anthropic.com>
@thodson-usgs thodson-usgs force-pushed the fix-sortby-tuple-4821 branch from ce5537d to 8e362ee Compare April 15, 2026 14:07
@thodson-usgs thodson-usgs marked this pull request as ready for review April 15, 2026 14:32
Comment thread xarray/core/dataset.py
def sortby(
self,
variables: (
Hashable
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you update the type hints as well?
Should probably be

str | DataArray | Iterable[Hashable | DataArray] | Callable[[Self], str | DataArray | Iterable[Hashable | DataArray]]

Same with the docstring and the DataArray method.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error when supplying a tuple of dimensions to DataArray.sortby()

2 participants