forked from pydata/xarray
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
93 lines (64 loc) · 2.27 KB
/
utils.py
File metadata and controls
93 lines (64 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from __future__ import annotations
import sys
from collections.abc import Hashable
from typing import TYPE_CHECKING, Any
import numpy as np
if TYPE_CHECKING:
if sys.version_info >= (3, 10):
from typing import TypeGuard
else:
from typing_extensions import TypeGuard
from numpy.typing import NDArray
from xarray.namedarray._typing import (
duckarray,
)
try:
from dask.array.core import Array as DaskArray
from dask.typing import DaskCollection
except ImportError:
DaskArray = NDArray # type: ignore
DaskCollection: Any = NDArray # type: ignore
def module_available(module: str) -> bool:
"""Checks whether a module is installed without importing it.
Use this for a lightweight check and lazy imports.
Parameters
----------
module : str
Name of the module.
Returns
-------
available : bool
Whether the module is installed.
"""
from importlib.util import find_spec
return find_spec(module) is not None
def is_dask_collection(x: object) -> TypeGuard[DaskCollection]:
if module_available("dask"):
from dask.typing import DaskCollection
return isinstance(x, DaskCollection)
return False
def is_duck_dask_array(x: duckarray[Any, Any]) -> TypeGuard[DaskArray]:
return is_dask_collection(x)
def to_0d_object_array(
value: object,
) -> NDArray[np.object_]:
"""Given a value, wrap it in a 0-D numpy.ndarray with dtype=object."""
result = np.empty((), dtype=object)
result[()] = value
return result
class ReprObject:
"""Object that prints as the given value, for use with sentinel values."""
__slots__ = ("_value",)
_value: str
def __init__(self, value: str):
self._value = value
def __repr__(self) -> str:
return self._value
def __eq__(self, other: ReprObject | Any) -> bool:
# TODO: What type can other be? ArrayLike?
return self._value == other._value if isinstance(other, ReprObject) else False
def __hash__(self) -> int:
return hash((type(self), self._value))
def __dask_tokenize__(self) -> Hashable:
from dask.base import normalize_token
return normalize_token((type(self), self._value)) # type: ignore[no-any-return]