Skip to content

Commit 4f1e2d3

Browse files
authored
Type annotate tests (#5728)
* Type annotate lots of tests * fixes for newer numpy version * . * .
1 parent 6b59d9a commit 4f1e2d3

40 files changed

+673
-644
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ Internal Changes
6363
By `Benoit Bovy <https://github.com/benbovy>`_.
6464
- Fix ``Mapping`` argument typing to allow mypy to pass on ``str`` keys (:pull:`5690`).
6565
By `Maximilian Roos <https://github.com/max-sixty>`_.
66+
- Annotate many of our tests, and fix some of the resulting typing errors. This will
67+
also mean our typing annotations are tested as part of CI. (:pull:`5728`).
68+
By `Maximilian Roos <https://github.com/max-sixty>`_.
6669
- Improve the performance of reprs for large datasets or dataarrays. (:pull:`5661`)
6770
By `Jimmy Westling <https://github.com/illviljan>`_.
6871
- Use isort's `float_to_top` config. (:pull:`5695`).

properties/test_encode_decode.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
@pytest.mark.slow
2727
@given(st.data(), an_array)
28-
def test_CFMask_coder_roundtrip(data, arr):
28+
def test_CFMask_coder_roundtrip(data, arr) -> None:
2929
names = data.draw(
3030
st.lists(st.text(), min_size=arr.ndim, max_size=arr.ndim, unique=True).map(
3131
tuple
@@ -39,7 +39,7 @@ def test_CFMask_coder_roundtrip(data, arr):
3939

4040
@pytest.mark.slow
4141
@given(st.data(), an_array)
42-
def test_CFScaleOffset_coder_roundtrip(data, arr):
42+
def test_CFScaleOffset_coder_roundtrip(data, arr) -> None:
4343
names = data.draw(
4444
st.lists(st.text(), min_size=arr.ndim, max_size=arr.ndim, unique=True).map(
4545
tuple

xarray/core/common.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,7 @@ def get_index(self, key: Hashable) -> pd.Index:
411411
return pd.Index(range(self.sizes[key]), name=key)
412412

413413
def _calc_assign_results(
414-
self: C, kwargs: Mapping[Hashable, Union[T, Callable[[C], T]]]
414+
self: C, kwargs: Mapping[Any, Union[T, Callable[[C], T]]]
415415
) -> Dict[Hashable, T]:
416416
return {k: v(self) if callable(v) else v for k, v in kwargs.items()}
417417

@@ -820,7 +820,7 @@ def rolling(
820820
self,
821821
dim: Mapping[Any, int] = None,
822822
min_periods: int = None,
823-
center: Union[bool, Mapping[Hashable, bool]] = False,
823+
center: Union[bool, Mapping[Any, bool]] = False,
824824
**window_kwargs: int,
825825
):
826826
"""
@@ -935,7 +935,7 @@ def coarsen(
935935
self,
936936
dim: Mapping[Any, int] = None,
937937
boundary: str = "exact",
938-
side: Union[str, Mapping[Hashable, str]] = "left",
938+
side: Union[str, Mapping[Any, str]] = "left",
939939
coord_func: str = "mean",
940940
**window_kwargs: int,
941941
):
@@ -1520,7 +1520,7 @@ def __getitem__(self, value):
15201520
def full_like(
15211521
other: "Dataset",
15221522
fill_value,
1523-
dtype: Union[DTypeLike, Mapping[Hashable, DTypeLike]] = None,
1523+
dtype: Union[DTypeLike, Mapping[Any, DTypeLike]] = None,
15241524
) -> "Dataset":
15251525
...
15261526

xarray/core/computation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ def _as_variables_or_variable(arg):
367367

368368

369369
def _unpack_dict_tuples(
370-
result_vars: Mapping[Hashable, Tuple[Variable, ...]], num_outputs: int
370+
result_vars: Mapping[Any, Tuple[Variable, ...]], num_outputs: int
371371
) -> Tuple[Dict[Hashable, Variable], ...]:
372372
out: Tuple[Dict[Hashable, Variable], ...] = tuple({} for _ in range(num_outputs))
373373
for name, values in result_vars.items():

xarray/core/coordinates.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
_THIS_ARRAY = ReprObject("<this-array>")
3232

3333

34-
class Coordinates(Mapping[Hashable, "DataArray"]):
34+
class Coordinates(Mapping[Any, "DataArray"]):
3535
__slots__ = ()
3636

3737
def __getitem__(self, key: Hashable) -> "DataArray":

xarray/core/dataarray.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ class DataArray(AbstractArray, DataWithCoords, DataArrayArithmetic):
366366
def __init__(
367367
self,
368368
data: Any = dtypes.NA,
369-
coords: Union[Sequence[Tuple], Mapping[Hashable, Any], None] = None,
369+
coords: Union[Sequence[Tuple], Mapping[Any, Any], None] = None,
370370
dims: Union[Hashable, Sequence[Hashable], None] = None,
371371
name: Hashable = None,
372372
attrs: Mapping = None,
@@ -788,7 +788,8 @@ def loc(self) -> _LocIndexer:
788788
return _LocIndexer(self)
789789

790790
@property
791-
def attrs(self) -> Dict[Hashable, Any]:
791+
# Key type needs to be `Any` because of mypy#4167
792+
def attrs(self) -> Dict[Any, Any]:
792793
"""Dictionary storing arbitrary metadata with this array."""
793794
return self.variable.attrs
794795

@@ -1068,7 +1069,7 @@ def chunk(
10681069
int,
10691070
Tuple[int, ...],
10701071
Tuple[Tuple[int, ...], ...],
1071-
Mapping[Hashable, Union[None, int, Tuple[int, ...]]],
1072+
Mapping[Any, Union[None, int, Tuple[int, ...]]],
10721073
] = {}, # {} even though it's technically unsafe, is being used intentionally here (#4667)
10731074
name_prefix: str = "xarray-",
10741075
token: str = None,
@@ -1312,7 +1313,7 @@ def sel(
13121313

13131314
def head(
13141315
self,
1315-
indexers: Union[Mapping[Hashable, int], int] = None,
1316+
indexers: Union[Mapping[Any, int], int] = None,
13161317
**indexers_kwargs: Any,
13171318
) -> "DataArray":
13181319
"""Return a new DataArray whose data is given by the the first `n`
@@ -1329,7 +1330,7 @@ def head(
13291330

13301331
def tail(
13311332
self,
1332-
indexers: Union[Mapping[Hashable, int], int] = None,
1333+
indexers: Union[Mapping[Any, int], int] = None,
13331334
**indexers_kwargs: Any,
13341335
) -> "DataArray":
13351336
"""Return a new DataArray whose data is given by the the last `n`
@@ -1346,7 +1347,7 @@ def tail(
13461347

13471348
def thin(
13481349
self,
1349-
indexers: Union[Mapping[Hashable, int], int] = None,
1350+
indexers: Union[Mapping[Any, int], int] = None,
13501351
**indexers_kwargs: Any,
13511352
) -> "DataArray":
13521353
"""Return a new DataArray whose data is given by each `n` value
@@ -1778,7 +1779,7 @@ def interp_like(
17781779

17791780
def rename(
17801781
self,
1781-
new_name_or_name_dict: Union[Hashable, Mapping[Hashable, Hashable]] = None,
1782+
new_name_or_name_dict: Union[Hashable, Mapping[Any, Hashable]] = None,
17821783
**names: Hashable,
17831784
) -> "DataArray":
17841785
"""Returns a new DataArray with renamed coordinates or a new name.
@@ -1874,7 +1875,7 @@ def swap_dims(
18741875

18751876
def expand_dims(
18761877
self,
1877-
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Hashable, Any]] = None,
1878+
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Any, Any]] = None,
18781879
axis=None,
18791880
**dim_kwargs: Any,
18801881
) -> "DataArray":
@@ -1926,7 +1927,7 @@ def expand_dims(
19261927

19271928
def set_index(
19281929
self,
1929-
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]] = None,
1930+
indexes: Mapping[Any, Union[Hashable, Sequence[Hashable]]] = None,
19301931
append: bool = False,
19311932
**indexes_kwargs: Union[Hashable, Sequence[Hashable]],
19321933
) -> "DataArray":
@@ -2014,7 +2015,7 @@ def reset_index(
20142015

20152016
def reorder_levels(
20162017
self,
2017-
dim_order: Mapping[Hashable, Sequence[int]] = None,
2018+
dim_order: Mapping[Any, Sequence[int]] = None,
20182019
**dim_order_kwargs: Sequence[int],
20192020
) -> "DataArray":
20202021
"""Rearrange index levels using input order.
@@ -2049,7 +2050,7 @@ def reorder_levels(
20492050

20502051
def stack(
20512052
self,
2052-
dimensions: Mapping[Hashable, Sequence[Hashable]] = None,
2053+
dimensions: Mapping[Any, Sequence[Hashable]] = None,
20532054
**dimensions_kwargs: Sequence[Hashable],
20542055
) -> "DataArray":
20552056
"""
@@ -3868,17 +3869,13 @@ def polyfit(
38683869

38693870
def pad(
38703871
self,
3871-
pad_width: Mapping[Hashable, Union[int, Tuple[int, int]]] = None,
3872+
pad_width: Mapping[Any, Union[int, Tuple[int, int]]] = None,
38723873
mode: str = "constant",
3873-
stat_length: Union[
3874-
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
3875-
] = None,
3874+
stat_length: Union[int, Tuple[int, int], Mapping[Any, Tuple[int, int]]] = None,
38763875
constant_values: Union[
3877-
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
3878-
] = None,
3879-
end_values: Union[
3880-
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
3876+
int, Tuple[int, int], Mapping[Any, Tuple[int, int]]
38813877
] = None,
3878+
end_values: Union[int, Tuple[int, int], Mapping[Any, Tuple[int, int]]] = None,
38823879
reflect_type: str = None,
38833880
**pad_width_kwargs: Any,
38843881
) -> "DataArray":

xarray/core/dataset.py

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def calculate_dimensions(variables: Mapping[Any, Variable]) -> Dict[Hashable, in
210210

211211

212212
def merge_indexes(
213-
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]],
213+
indexes: Mapping[Any, Union[Hashable, Sequence[Hashable]]],
214214
variables: Mapping[Any, Variable],
215215
coord_names: Set[Hashable],
216216
append: bool = False,
@@ -510,7 +510,7 @@ def _initialize_feasible(lb, ub):
510510
return param_defaults, bounds_defaults
511511

512512

513-
class DataVariables(Mapping[Hashable, "DataArray"]):
513+
class DataVariables(Mapping[Any, "DataArray"]):
514514
__slots__ = ("_dataset",)
515515

516516
def __init__(self, dataset: "Dataset"):
@@ -2110,7 +2110,7 @@ def chunk(
21102110
chunks: Union[
21112111
int,
21122112
str,
2113-
Mapping[Hashable, Union[None, int, str, Tuple[int, ...]]],
2113+
Mapping[Any, Union[None, int, str, Tuple[int, ...]]],
21142114
] = {}, # {} even though it's technically unsafe, is being used intentionally here (#4667)
21152115
name_prefix: str = "xarray-",
21162116
token: str = None,
@@ -2485,7 +2485,7 @@ def sel(
24852485

24862486
def head(
24872487
self,
2488-
indexers: Union[Mapping[Hashable, int], int] = None,
2488+
indexers: Union[Mapping[Any, int], int] = None,
24892489
**indexers_kwargs: Any,
24902490
) -> "Dataset":
24912491
"""Returns a new dataset with the first `n` values of each array
@@ -2531,7 +2531,7 @@ def head(
25312531

25322532
def tail(
25332533
self,
2534-
indexers: Union[Mapping[Hashable, int], int] = None,
2534+
indexers: Union[Mapping[Any, int], int] = None,
25352535
**indexers_kwargs: Any,
25362536
) -> "Dataset":
25372537
"""Returns a new dataset with the last `n` values of each array
@@ -2580,7 +2580,7 @@ def tail(
25802580

25812581
def thin(
25822582
self,
2583-
indexers: Union[Mapping[Hashable, int], int] = None,
2583+
indexers: Union[Mapping[Any, int], int] = None,
25842584
**indexers_kwargs: Any,
25852585
) -> "Dataset":
25862586
"""Returns a new dataset with each array indexed along every `n`-th
@@ -3559,7 +3559,7 @@ def swap_dims(
35593559

35603560
def expand_dims(
35613561
self,
3562-
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Hashable, Any]] = None,
3562+
dim: Union[None, Hashable, Sequence[Hashable], Mapping[Any, Any]] = None,
35633563
axis: Union[None, int, Sequence[int]] = None,
35643564
**dim_kwargs: Any,
35653565
) -> "Dataset":
@@ -3691,7 +3691,7 @@ def expand_dims(
36913691

36923692
def set_index(
36933693
self,
3694-
indexes: Mapping[Hashable, Union[Hashable, Sequence[Hashable]]] = None,
3694+
indexes: Mapping[Any, Union[Hashable, Sequence[Hashable]]] = None,
36953695
append: bool = False,
36963696
**indexes_kwargs: Union[Hashable, Sequence[Hashable]],
36973697
) -> "Dataset":
@@ -3789,7 +3789,7 @@ def reset_index(
37893789

37903790
def reorder_levels(
37913791
self,
3792-
dim_order: Mapping[Hashable, Sequence[int]] = None,
3792+
dim_order: Mapping[Any, Sequence[int]] = None,
37933793
**dim_order_kwargs: Sequence[int],
37943794
) -> "Dataset":
37953795
"""Rearrange index levels using input order.
@@ -3858,7 +3858,7 @@ def _stack_once(self, dims, new_dim):
38583858

38593859
def stack(
38603860
self,
3861-
dimensions: Mapping[Hashable, Sequence[Hashable]] = None,
3861+
dimensions: Mapping[Any, Sequence[Hashable]] = None,
38623862
**dimensions_kwargs: Sequence[Hashable],
38633863
) -> "Dataset":
38643864
"""
@@ -6929,17 +6929,13 @@ def polyfit(
69296929

69306930
def pad(
69316931
self,
6932-
pad_width: Mapping[Hashable, Union[int, Tuple[int, int]]] = None,
6932+
pad_width: Mapping[Any, Union[int, Tuple[int, int]]] = None,
69336933
mode: str = "constant",
6934-
stat_length: Union[
6935-
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
6936-
] = None,
6934+
stat_length: Union[int, Tuple[int, int], Mapping[Any, Tuple[int, int]]] = None,
69376935
constant_values: Union[
6938-
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
6939-
] = None,
6940-
end_values: Union[
6941-
int, Tuple[int, int], Mapping[Hashable, Tuple[int, int]]
6936+
int, Tuple[int, int], Mapping[Any, Tuple[int, int]]
69426937
] = None,
6938+
end_values: Union[int, Tuple[int, int], Mapping[Any, Tuple[int, int]]] = None,
69436939
reflect_type: str = None,
69446940
**pad_width_kwargs: Any,
69456941
) -> "Dataset":

xarray/core/indexes.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class Index:
3434

3535
@classmethod
3636
def from_variables(
37-
cls, variables: Mapping[Hashable, "Variable"]
37+
cls, variables: Mapping[Any, "Variable"]
3838
) -> Tuple["Index", Optional[IndexVars]]: # pragma: no cover
3939
raise NotImplementedError()
4040

@@ -153,7 +153,7 @@ def __init__(self, array: Any, dim: Hashable):
153153
self.dim = dim
154154

155155
@classmethod
156-
def from_variables(cls, variables: Mapping[Hashable, "Variable"]):
156+
def from_variables(cls, variables: Mapping[Any, "Variable"]):
157157
from .variable import IndexVariable
158158

159159
if len(variables) != 1:
@@ -291,7 +291,7 @@ def _create_variables_from_multiindex(index, dim, level_meta=None):
291291

292292
class PandasMultiIndex(PandasIndex):
293293
@classmethod
294-
def from_variables(cls, variables: Mapping[Hashable, "Variable"]):
294+
def from_variables(cls, variables: Mapping[Any, "Variable"]):
295295
if any([var.ndim != 1 for var in variables.values()]):
296296
raise ValueError("PandasMultiIndex only accepts 1-dimensional variables")
297297

@@ -499,7 +499,7 @@ def isel_variable_and_index(
499499
name: Hashable,
500500
variable: "Variable",
501501
index: Index,
502-
indexers: Mapping[Hashable, Union[int, slice, np.ndarray, "Variable"]],
502+
indexers: Mapping[Any, Union[int, slice, np.ndarray, "Variable"]],
503503
) -> Tuple["Variable", Optional[Index]]:
504504
"""Index a Variable and an Index together.
505505

0 commit comments

Comments
 (0)