Skip to content

Commit cbcc035

Browse files
Import dask and cubed only once (#457)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 8cfd999 commit cbcc035

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

flox/xrutils.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import datetime
55
import importlib
66
from collections.abc import Iterable
7+
from types import ModuleType
78
from typing import Any
89

910
import numpy as np
@@ -45,13 +46,20 @@ def module_available(module: str, minversion: str | None = None) -> bool:
4546
except ImportError:
4647
cftime = None
4748

49+
cubed: ModuleType | None
50+
try:
51+
import cubed # type: ignore[no-redef]
52+
except ImportError:
53+
cubed = None
4854

55+
dask: ModuleType | None
4956
try:
5057
import dask.array
5158

52-
dask_array_type = dask.array.Array
59+
dask_array_type = dask.array.Array # type: ignore[union-attr]
5360
except ImportError:
54-
dask_array_type = () # type: ignore[assignment, misc]
61+
dask = None
62+
dask_array_type = ()
5563

5664

5765
def asarray(data, xp=np):
@@ -79,26 +87,19 @@ def is_chunked_array(x) -> bool:
7987

8088

8189
def is_dask_collection(x):
82-
try:
83-
import dask
84-
85-
return dask.is_dask_collection(x)
86-
87-
except ImportError:
90+
if dask is None:
8891
return False
92+
return dask.is_dask_collection(x)
8993

9094

9195
def is_duck_dask_array(x):
9296
return is_duck_array(x) and is_dask_collection(x)
9397

9498

9599
def is_duck_cubed_array(x):
96-
try:
97-
import cubed
98-
99-
return is_duck_array(x) and isinstance(x, cubed.Array)
100-
except ImportError:
100+
if cubed is None:
101101
return False
102+
return is_duck_array(x) and isinstance(x, cubed.Array)
102103

103104

104105
class ReprObject:
@@ -140,7 +141,7 @@ def is_scalar(value: Any, include_0d: bool = True) -> bool:
140141
or isinstance(value, str | bytes | dict)
141142
or not (
142143
isinstance(value, (Iterable,) + NON_NUMPY_SUPPORTED_ARRAY_TYPES)
143-
or hasattr(value, "__array_function__")
144+
or hasattr(value, "__array_function__") # type: ignore[unreachable]
144145
)
145146
)
146147

@@ -182,13 +183,13 @@ def isnull(data: Any):
182183
else:
183184
# at this point, array should have dtype=object
184185
if isinstance(data, (np.ndarray, dask_array_type)): # noqa
185-
return pd.isnull(data) # type: ignore[arg-type]
186+
return pd.isnull(data)
186187
else:
187188
# Not reachable yet, but intended for use with other duck array
188189
# types. For full consistency with pandas, we should accept None as
189190
# a null value as well as NaN, but it isn't clear how to do this
190191
# with duck typing.
191-
return data != data
192+
return data != data # type: ignore[unreachable]
192193

193194

194195
def datetime_to_numeric(array, offset=None, datetime_unit=None, dtype=float):

0 commit comments

Comments
 (0)