Skip to content

Fix numpy 1.20 incompatibility #6821

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

Merged
merged 4 commits into from
Jul 30, 2022
Merged
Show file tree
Hide file tree
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 doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ Bug fixes
~~~~~~~~~

- :py:attr:`DataArray.nbytes` now uses the ``nbytes`` property of the underlying array if available.
(:pull:`6797`)
By `Max Jones <https://github.com/maxrjones>`_.
- Fix incompatibility with numpy 1.20 (:issue:`6818`, :pull:`6821`)
By `Michael Niklas <https://github.com/headtr1ck>`_.

Documentation
~~~~~~~~~~~~~
Expand Down
42 changes: 21 additions & 21 deletions xarray/core/npcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
Any,
List,
Literal,
Protocol,
Sequence,
Tuple,
Type,
Expand All @@ -43,10 +44,26 @@
import numpy as np
from packaging.version import Version

if TYPE_CHECKING:

class _SupportsArray(Protocol):
def __array__(self) -> np.ndarray:
...

# once NumPy 1.21 is minimum version, use NumPys definition directly
class _SupportsDType(Protocol):
@property
def dtype(self) -> np.dtype:
...

else:
_SupportsArray = Any
_SupportsDType = Any

# Type annotations stubs
try:
from numpy.typing import ArrayLike, DTypeLike
from numpy.typing._dtype_like import _DTypeLikeNested, _ShapeLike, _SupportsDType
from numpy.typing._dtype_like import _DTypeLikeNested, _ShapeLike

# Xarray requires a Mapping[Hashable, dtype] in many places which
# conflics with numpys own DTypeLike (with dtypes for fields).
Expand All @@ -69,27 +86,10 @@
# because numpy does the same?
List[Any],
# anything with a dtype attribute
_SupportsDType[np.dtype],
_SupportsDType,
]
except ImportError:
# fall back for numpy < 1.20, ArrayLike adapted from numpy.typing._array_like
from typing import Protocol

if TYPE_CHECKING:

class _SupportsArray(Protocol):
def __array__(self) -> np.ndarray:
...

class _SupportsDTypeFallback(Protocol):
@property
def dtype(self) -> np.dtype:
...

else:
_SupportsArray = Any
_SupportsDTypeFallback = Any

# fall back for numpy < 1.20
_T = TypeVar("_T")
_NestedSequence = Union[
_T,
Expand Down Expand Up @@ -120,7 +120,7 @@ def dtype(self) -> np.dtype:
Type[Any],
Tuple[Any, Any],
List[Any],
_SupportsDTypeFallback,
_SupportsDType,
]
DTypeLike = DTypeLikeSave # type: ignore[misc]

Expand Down