Skip to content
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

Handle numpy missing the array api function astype #8315

Merged
merged 1 commit into from
Oct 16, 2023
Merged
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
3 changes: 3 additions & 0 deletions xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,9 @@ def cumulative_trapezoid(y, x, axis):
def astype(data, dtype, **kwargs):
if hasattr(data, "__array_namespace__"):
xp = get_array_namespace(data)
if xp == np:
Copy link
Contributor

Choose a reason for hiding this comment

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

The namespace for numpy is numpy.array_api and np.array_api.astype exists. It seems like this should just work.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is how our get_array_namespace works:

def get_array_namespace(x):
if hasattr(x, "__array_namespace__"):
return x.__array_namespace__()
else:
return np

Which usually works. But not for astype.

Using np.array_api doesn't work because you have to use np.array_api.Array instead of np.ndarray:

import numpy.array_api as nxp
nxp.astype(np.array([1, 2,]), np.dtype(float))

Traceback (most recent call last):

  File "C:\Users\J.W\AppData\Local\Temp\ipykernel_8616\23329947.py", line 1, in <cell line: 1>
    nxp.astype(np.array([1, 2,]), np.dtype(float))

  File "C:\Users\J.W\anaconda3\envs\xarray-tests\lib\site-packages\numpy\array_api\_data_type_functions.py", line 20, in astype
    return Array._new(x._array.astype(dtype=dtype, copy=copy))

AttributeError: 'numpy.ndarray' object has no attribute '_array'

I found it simpler to just change astype here.

# numpy currently doesn't have a astype:
return data.astype(dtype, **kwargs)
return xp.astype(data, dtype, **kwargs)
return data.astype(dtype, **kwargs)

Expand Down
Loading