Skip to content

Commit d4153f1

Browse files
authored
Upgrade mypy to 1.11 (#9417)
* Upgrade mypy to 1.11 This does a few things: - Upgrades mypy - Adds lots of ignores for mpl & pandas type issues in tests -- not as good as fixing them, but better than staying on mypy 1.8 - Removes some old ignores - Adds a couple of ignores with notes where it's our issue and I'm not sure what's going on - Starts using the `EllipsisType` in a couple of places Note that I used a tool to mass-add ignores, I didn't add them all manually
1 parent cba1de5 commit d4153f1

15 files changed

+108
-109
lines changed

.github/workflows/ci-additional.yaml

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ jobs:
123123
python xarray/util/print_versions.py
124124
- name: Install mypy
125125
run: |
126-
python -m pip install "mypy<1.9" --force-reinstall
126+
python -m pip install "mypy" --force-reinstall
127127
128128
- name: Run mypy
129129
run: |
@@ -177,7 +177,7 @@ jobs:
177177
python xarray/util/print_versions.py
178178
- name: Install mypy
179179
run: |
180-
python -m pip install "mypy<1.9" --force-reinstall
180+
python -m pip install "mypy" --force-reinstall
181181
182182
- name: Run mypy
183183
run: |
@@ -187,22 +187,20 @@ jobs:
187187
uses: codecov/[email protected]
188188
with:
189189
file: mypy_report/cobertura.xml
190-
flags: mypy39
190+
flags: mypy-min
191191
env_vars: PYTHON_VERSION
192192
name: codecov-umbrella
193193
fail_ci_if_error: false
194194

195-
196-
197195
pyright:
198196
name: Pyright
199197
runs-on: "ubuntu-latest"
200198
needs: detect-ci-trigger
201199
if: |
202-
always()
203-
&& (
204-
contains( github.event.pull_request.labels.*.name, 'run-pyright')
205-
)
200+
always()
201+
&& (
202+
contains( github.event.pull_request.labels.*.name, 'run-pyright')
203+
)
206204
defaults:
207205
run:
208206
shell: bash -l {0}
@@ -258,10 +256,10 @@ jobs:
258256
runs-on: "ubuntu-latest"
259257
needs: detect-ci-trigger
260258
if: |
261-
always()
262-
&& (
263-
contains( github.event.pull_request.labels.*.name, 'run-pyright')
264-
)
259+
always()
260+
&& (
261+
contains( github.event.pull_request.labels.*.name, 'run-pyright')
262+
)
265263
defaults:
266264
run:
267265
shell: bash -l {0}
@@ -312,8 +310,6 @@ jobs:
312310
name: codecov-umbrella
313311
fail_ci_if_error: false
314312

315-
316-
317313
min-version-policy:
318314
name: Minimum Version Policy
319315
runs-on: "ubuntu-latest"

xarray/core/accessor_str.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -847,7 +847,7 @@ def normalize(
847847
normalized : same type as values
848848
849849
"""
850-
return self._apply(func=lambda x: normalize(form, x))
850+
return self._apply(func=lambda x: normalize(form, x)) # type: ignore[arg-type]
851851

852852
def isalnum(self) -> T_DataArray:
853853
"""

xarray/core/dataarray.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
)
1313
from functools import partial
1414
from os import PathLike
15+
from types import EllipsisType
1516
from typing import (
1617
TYPE_CHECKING,
1718
Any,
@@ -2841,7 +2842,7 @@ def stack(
28412842
dim: Mapping[Any, Sequence[Hashable]] | None = None,
28422843
create_index: bool | None = True,
28432844
index_cls: type[Index] = PandasMultiIndex,
2844-
**dim_kwargs: Sequence[Hashable],
2845+
**dim_kwargs: Sequence[Hashable | EllipsisType],
28452846
) -> Self:
28462847
"""
28472848
Stack any number of existing dimensions into a single new dimension.

xarray/core/dataset.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from numbers import Number
2424
from operator import methodcaller
2525
from os import PathLike
26+
from types import EllipsisType
2627
from typing import IO, TYPE_CHECKING, Any, Generic, Literal, cast, overload
2728

2829
import numpy as np
@@ -5364,10 +5365,10 @@ def _stack_once(
53645365
@partial(deprecate_dims, old_name="dimensions")
53655366
def stack(
53665367
self,
5367-
dim: Mapping[Any, Sequence[Hashable | ellipsis]] | None = None,
5368+
dim: Mapping[Any, Sequence[Hashable | EllipsisType]] | None = None,
53685369
create_index: bool | None = True,
53695370
index_cls: type[Index] = PandasMultiIndex,
5370-
**dim_kwargs: Sequence[Hashable | ellipsis],
5371+
**dim_kwargs: Sequence[Hashable | EllipsisType],
53715372
) -> Self:
53725373
"""
53735374
Stack any number of existing dimensions into a single new dimension.

xarray/core/datatree.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,8 +234,7 @@ def __getitem__(self, key: Mapping) -> Dataset: # type: ignore[overload-overlap
234234
...
235235

236236
@overload
237-
def __getitem__(self, key: Hashable) -> DataArray: # type: ignore[overload-overlap]
238-
...
237+
def __getitem__(self, key: Hashable) -> DataArray: ...
239238

240239
# See: https://github.com/pydata/xarray/issues/8855
241240
@overload

xarray/core/weighted.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ def _weight_check(w):
182182
if is_duck_dask_array(weights.data):
183183
# assign to copy - else the check is not triggered
184184
weights = weights.copy(
185-
data=weights.data.map_blocks(_weight_check, dtype=weights.dtype),
185+
data=weights.data.map_blocks(_weight_check, dtype=weights.dtype), # type: ignore[call-arg, arg-type]
186186
deep=False,
187187
)
188188

@@ -264,7 +264,9 @@ def _sum_of_squares(
264264

265265
demeaned = da - da.weighted(self.weights).mean(dim=dim)
266266

267-
return self._reduce((demeaned**2), self.weights, dim=dim, skipna=skipna)
267+
# TODO: unsure why mypy complains about these being DataArray return types
268+
# rather than T_DataArray?
269+
return self._reduce((demeaned**2), self.weights, dim=dim, skipna=skipna) # type: ignore[return-value]
268270

269271
def _weighted_sum(
270272
self,
@@ -274,7 +276,7 @@ def _weighted_sum(
274276
) -> T_DataArray:
275277
"""Reduce a DataArray by a weighted ``sum`` along some dimension(s)."""
276278

277-
return self._reduce(da, self.weights, dim=dim, skipna=skipna)
279+
return self._reduce(da, self.weights, dim=dim, skipna=skipna) # type: ignore[return-value]
278280

279281
def _weighted_mean(
280282
self,

xarray/plot/dataset_plot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -697,7 +697,7 @@ def wrapper(dataset_plotfunc: F) -> F:
697697
dataset_plotfunc.__doc__ = ds_doc
698698
return dataset_plotfunc
699699

700-
return wrapper
700+
return wrapper # type: ignore[return-value]
701701

702702

703703
def _normalize_args(

xarray/tests/test_backends.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ def test_roundtrip_cftime_datetime_data(self) -> None:
595595
assert actual.t.encoding["calendar"] == expected_calendar
596596

597597
def test_roundtrip_timedelta_data(self) -> None:
598-
time_deltas = pd.to_timedelta(["1h", "2h", "NaT"])
598+
time_deltas = pd.to_timedelta(["1h", "2h", "NaT"]) # type: ignore[arg-type, unused-ignore]
599599
expected = Dataset({"td": ("td", time_deltas), "td0": time_deltas[0]})
600600
with self.roundtrip(expected) as actual:
601601
assert_identical(expected, actual)
@@ -2204,7 +2204,7 @@ def create_store(self):
22042204
store_target, mode="w", **self.version_kwargs
22052205
)
22062206

2207-
def save(self, dataset, store_target, **kwargs):
2207+
def save(self, dataset, store_target, **kwargs): # type: ignore[override]
22082208
return dataset.to_zarr(store=store_target, **kwargs, **self.version_kwargs)
22092209

22102210
@contextlib.contextmanager

xarray/tests/test_backends_api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def open_dataset(
6969
class PassThroughBackendEntrypoint(xr.backends.BackendEntrypoint):
7070
"""Access an object passed to the `open_dataset` method."""
7171

72-
def open_dataset(self, dataset, *, drop_variables=None):
72+
def open_dataset(self, dataset, *, drop_variables=None): # type: ignore[override]
7373
"""Return the first argument."""
7474
return dataset
7575

xarray/tests/test_coding_times.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -628,10 +628,10 @@ def test_cf_timedelta_2d() -> None:
628628
@pytest.mark.parametrize(
629629
["deltas", "expected"],
630630
[
631-
(pd.to_timedelta(["1 day", "2 days"]), "days"),
632-
(pd.to_timedelta(["1h", "1 day 1 hour"]), "hours"),
633-
(pd.to_timedelta(["1m", "2m", np.nan]), "minutes"),
634-
(pd.to_timedelta(["1m3s", "1m4s"]), "seconds"),
631+
(pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore]
632+
(pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore]
633+
(pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore]
634+
(pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore]
635635
],
636636
)
637637
def test_infer_timedelta_units(deltas, expected) -> None:

xarray/tests/test_conventions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def test_incompatible_attributes(self) -> None:
119119
Variable(
120120
["t"], pd.date_range("2000-01-01", periods=3), {"units": "foobar"}
121121
),
122-
Variable(["t"], pd.to_timedelta(["1 day"]), {"units": "foobar"}),
122+
Variable(["t"], pd.to_timedelta(["1 day"]), {"units": "foobar"}), # type: ignore[arg-type, unused-ignore]
123123
Variable(["t"], [0, 1, 2], {"add_offset": 0}, {"add_offset": 2}),
124124
Variable(["t"], [0, 1, 2], {"_FillValue": 0}, {"_FillValue": 2}),
125125
]

xarray/tests/test_dataarray.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7159,7 +7159,7 @@ def test_result_as_expected(self) -> None:
71597159
def test_error_on_ellipsis_without_list(self) -> None:
71607160
da = DataArray([[1, 2], [1, 2]], dims=("x", "y"))
71617161
with pytest.raises(ValueError):
7162-
da.stack(flat=...)
7162+
da.stack(flat=...) # type: ignore
71637163

71647164

71657165
def test_nD_coord_dataarray() -> None:

xarray/tests/test_formatting.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,9 @@ def test_format_items(self) -> None:
118118
np.arange(4) * np.timedelta64(500, "ms"),
119119
"00:00:00 00:00:00.500000 00:00:01 00:00:01.500000",
120120
),
121-
(pd.to_timedelta(["NaT", "0s", "1s", "NaT"]), "NaT 00:00:00 00:00:01 NaT"),
121+
(pd.to_timedelta(["NaT", "0s", "1s", "NaT"]), "NaT 00:00:00 00:00:01 NaT"), # type: ignore[arg-type, unused-ignore]
122122
(
123-
pd.to_timedelta(["1 day 1 hour", "1 day", "0 hours"]),
123+
pd.to_timedelta(["1 day 1 hour", "1 day", "0 hours"]), # type: ignore[arg-type, unused-ignore]
124124
"1 days 01:00:00 1 days 00:00:00 0 days 00:00:00",
125125
),
126126
([1, 2, 3], "1 2 3"),

0 commit comments

Comments
 (0)