-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Allow selecting variables using a list with mixed data types #5394
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
Conversation
xarray/core/dataset.py
Outdated
@@ -1485,7 +1485,7 @@ def __getitem__(self, key): | |||
if hashable(key): | |||
return self._construct_dataarray(key) | |||
else: | |||
return self._copy_listed(np.asarray(key)) | |||
return self._copy_listed(np.asarray(key, dtype="O")) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is np.asarray
needed here?
Can we just check that key
is a list, and raise an error otherwise.
Right now, if key
is for example a set (i.e., ds[set(["foo"])]
), an error is raised anyways because np.asarray
creates a 0-d array and iteration is not possible. The error is not raised directly by xarray
though and I think it's not very clear, especially because the original set is iterable.
Also, is the goal to only allow lists? Does it make sense to allow any iterable?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Line 1345 in 5d367db
for name in names: |
Seems to only be used to loop through in
._copy_listed
. I can't really think of a reason why it has to be forced to ndarray? names is also typed as an Iterable[Hashable], so I suppose it makes sense to allow any iterable.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does anything break if we remove it?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All tests look OK removing np.asarray
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great! Without wanting to ignore Chesterton's fence — let's do it unless we hear objections in the next day or so.
@malmans2 feel free to add a whatsnew in another PR! |
...and thank you for this contribution! |
pre-commit run --all-files
whats-new.rst
Lists passed to
__getitem__
are converted to arrays.np.asarray
infers the dtype, and for example converts a list with str and int to an array of str. Forcingdtype="O"
fixes the issue.