pydata / pydata/xarray

`sel` fails confusingly or silently when a dimension name matches an optional argument

Open
#3,324 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

Given that many Xarray methods accept dict or keyword arguments, this may effect other methods. That said, here is a minimal example with sel.

Minimal example

If I want to select based on a dimension named method, I cannot because Xarray thinks method is the method argument to sel:

>>> da1 = xr.DataArray(range(3), dims=['method'], coords={'method': range(3)})
>>> da1
<xarray.DataArray (method: 3)>
array([0, 1, 2])
Coordinates:
  * method   (method) int64 0 1 2
>>> da1.sel(method=0)
...
TypeError: ``method`` must be a string

And if the method dimension has string labels, this fails silently:

>>> da2 = xr.DataArray(range(3), dims=['method'], coords={'method': list('abc')})
>>> da2.sel(method='a')
<xarray.DataArray (method: 3)>
array([0, 1, 2])
Coordinates:
  * method   (method) <U1 'a' 'b' 'c'
Expected Output

I think raising a ValueError and providing a clarifying error message is the right call, but maybe the maintainers have a different opinion. At the very least, it seems like Xarray could note that the DataArray instance has a dimension that matches one of the function arguments and ask the user to use dict-like arguments if required.

I imagine a general error handling function could be written to check this for any function and DataArray pair.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the minimal DataArray.sel examples in the issue and inspect the sel entry point and its handling of keyword arguments. Trace how a dimension named method is interpreted, then add focused regression coverage for the numeric and string-label cases. Done means the collision is detected with a clear outcome, or the supported dict-like workaround is clearly enforced and tested.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
data
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.