Skip to content

Commit 47eec7f

Browse files
Remove real, imag, astype methods from NamedArray (#8295)
* remove imag / real / astype * Remove real, imag and astype * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * add imag, real functions * Update variable.py * Update utils.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update utils.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 338fc92 commit 47eec7f

File tree

3 files changed

+55
-37
lines changed

3 files changed

+55
-37
lines changed

xarray/core/variable.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2400,6 +2400,28 @@ def notnull(self, keep_attrs: bool | None = None):
24002400
keep_attrs=keep_attrs,
24012401
)
24022402

2403+
@property
2404+
def real(self):
2405+
"""
2406+
The real part of the variable.
2407+
2408+
See Also
2409+
--------
2410+
numpy.ndarray.real
2411+
"""
2412+
return self._replace(data=self.data.real)
2413+
2414+
@property
2415+
def imag(self):
2416+
"""
2417+
The imaginary part of the variable.
2418+
2419+
See Also
2420+
--------
2421+
numpy.ndarray.imag
2422+
"""
2423+
return self._replace(data=self.data.imag)
2424+
24032425
def __array_wrap__(self, obj, context=None):
24042426
return Variable(self.dims, obj)
24052427

xarray/namedarray/core.py

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
Default,
1515
T_DuckArray,
1616
_default,
17+
astype,
1718
is_chunked_duck_array,
1819
is_duck_array,
1920
is_duck_dask_array,
@@ -245,28 +246,6 @@ def data(self, data: T_DuckArray | np.typing.ArrayLike) -> None:
245246
self._check_shape(data)
246247
self._data = data
247248

248-
@property
249-
def real(self) -> Self:
250-
"""
251-
The real part of the NamedArray.
252-
253-
See Also
254-
--------
255-
numpy.ndarray.real
256-
"""
257-
return self._replace(data=self.data.real)
258-
259-
@property
260-
def imag(self) -> Self:
261-
"""
262-
The imaginary part of the NamedArray.
263-
264-
See Also
265-
--------
266-
numpy.ndarray.imag
267-
"""
268-
return self._replace(data=self.data.imag)
269-
270249
def __dask_tokenize__(self) -> Hashable:
271250
# Use v.data, instead of v._data, in order to cope with the wrappers
272251
# around NetCDF and the like
@@ -497,7 +476,7 @@ def _as_sparse(
497476
except AttributeError as exc:
498477
raise ValueError(f"{sparse_format} is not a valid sparse format") from exc
499478

500-
data = as_sparse(self.data.astype(dtype), fill_value=fill_value)
479+
data = as_sparse(astype(self.data, dtype), fill_value=fill_value)
501480
return self._replace(data=data)
502481

503482
def _to_dense(self) -> Self:

xarray/namedarray/utils.py

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import sys
55
from collections.abc import Hashable
66
from enum import Enum
7+
from types import ModuleType
78
from typing import TYPE_CHECKING, Any, Final, Protocol, TypeVar
89

910
import numpy as np
@@ -15,9 +16,9 @@
1516
from typing_extensions import TypeGuard
1617

1718
if sys.version_info >= (3, 11):
18-
from typing import Self
19+
pass
1920
else:
20-
from typing_extensions import Self
21+
pass
2122

2223
try:
2324
from dask.array import Array as DaskArray
@@ -29,7 +30,7 @@
2930

3031
# https://stackoverflow.com/questions/74633074/how-to-type-hint-a-generic-numpy-array
3132
T_DType_co = TypeVar("T_DType_co", bound=np.dtype[np.generic], covariant=True)
32-
# T_DType = TypeVar("T_DType", bound=np.dtype[np.generic])
33+
T_DType = TypeVar("T_DType", bound=np.dtype[np.generic])
3334

3435

3536
class _Array(Protocol[T_DType_co]):
@@ -41,17 +42,6 @@ def dtype(self) -> T_DType_co:
4142
def shape(self) -> tuple[int, ...]:
4243
...
4344

44-
@property
45-
def real(self) -> Self:
46-
...
47-
48-
@property
49-
def imag(self) -> Self:
50-
...
51-
52-
def astype(self, dtype: np.typing.DTypeLike) -> Self:
53-
...
54-
5545
# TODO: numpy doesn't use any inputs:
5646
# https://github.com/numpy/numpy/blob/v1.24.3/numpy/_typing/_array_like.py#L38
5747
def __array__(self) -> np.ndarray[Any, T_DType_co]:
@@ -161,3 +151,30 @@ def __dask_tokenize__(self) -> Hashable:
161151
from dask.base import normalize_token
162152

163153
return normalize_token((type(self), self._value)) # type: ignore[no-any-return]
154+
155+
156+
# %% Array API functions
157+
def get_array_namespace(x: _Array[Any]) -> ModuleType:
158+
if hasattr(x, "__array_namespace__"):
159+
return x.__array_namespace__() # type: ignore[no-any-return]
160+
else:
161+
return np
162+
163+
164+
def astype(x: _Array[Any], dtype: T_DType, /, *, copy: bool = True) -> _Array[T_DType]:
165+
if hasattr(x, "__array_namespace__"):
166+
xp = x.__array_namespace__()
167+
return xp.astype(x, dtype, copy=copy) # type: ignore[no-any-return]
168+
169+
# np.astype doesn't exist yet:
170+
return x.astype(dtype, copy=copy) # type: ignore[no-any-return, attr-defined]
171+
172+
173+
def imag(x: _Array[Any], /) -> _Array[Any]:
174+
xp = get_array_namespace(x)
175+
return xp.imag(x) # type: ignore[no-any-return]
176+
177+
178+
def real(x: _Array[Any], /) -> _Array[Any]:
179+
xp = get_array_namespace(x)
180+
return xp.real(x) # type: ignore[no-any-return]

0 commit comments

Comments
 (0)