From c916fe70c2c7cb7c48cf60cdbbc68ba20efe6803 Mon Sep 17 00:00:00 2001 From: Maximilian Roos <5635139+max-sixty@users.noreply.github.com> Date: Sat, 31 Aug 2024 12:40:01 -0700 Subject: [PATCH] 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 --- .github/workflows/ci-additional.yaml | 26 +++-- xarray/core/accessor_str.py | 2 +- xarray/core/dataarray.py | 3 +- xarray/core/dataset.py | 5 +- xarray/core/datatree.py | 3 +- xarray/core/weighted.py | 8 +- xarray/plot/dataset_plot.py | 2 +- xarray/tests/test_backends.py | 4 +- xarray/tests/test_backends_api.py | 2 +- xarray/tests/test_coding_times.py | 8 +- xarray/tests/test_conventions.py | 2 +- xarray/tests/test_dataarray.py | 2 +- xarray/tests/test_formatting.py | 4 +- xarray/tests/test_plot.py | 138 +++++++++++++-------------- xarray/tests/test_plugins.py | 8 +- 15 files changed, 108 insertions(+), 109 deletions(-) diff --git a/.github/workflows/ci-additional.yaml b/.github/workflows/ci-additional.yaml index 56faa89e571..21981e76cec 100644 --- a/.github/workflows/ci-additional.yaml +++ b/.github/workflows/ci-additional.yaml @@ -123,7 +123,7 @@ jobs: python xarray/util/print_versions.py - name: Install mypy run: | - python -m pip install "mypy<1.9" --force-reinstall + python -m pip install "mypy" --force-reinstall - name: Run mypy run: | @@ -177,7 +177,7 @@ jobs: python xarray/util/print_versions.py - name: Install mypy run: | - python -m pip install "mypy<1.9" --force-reinstall + python -m pip install "mypy" --force-reinstall - name: Run mypy run: | @@ -187,22 +187,20 @@ jobs: uses: codecov/codecov-action@v4.5.0 with: file: mypy_report/cobertura.xml - flags: mypy39 + flags: mypy-min env_vars: PYTHON_VERSION name: codecov-umbrella fail_ci_if_error: false - - pyright: name: Pyright runs-on: "ubuntu-latest" needs: detect-ci-trigger if: | - always() - && ( - contains( github.event.pull_request.labels.*.name, 'run-pyright') - ) + always() + && ( + contains( github.event.pull_request.labels.*.name, 'run-pyright') + ) defaults: run: shell: bash -l {0} @@ -258,10 +256,10 @@ jobs: runs-on: "ubuntu-latest" needs: detect-ci-trigger if: | - always() - && ( - contains( github.event.pull_request.labels.*.name, 'run-pyright') - ) + always() + && ( + contains( github.event.pull_request.labels.*.name, 'run-pyright') + ) defaults: run: shell: bash -l {0} @@ -312,8 +310,6 @@ jobs: name: codecov-umbrella fail_ci_if_error: false - - min-version-policy: name: Minimum Version Policy runs-on: "ubuntu-latest" diff --git a/xarray/core/accessor_str.py b/xarray/core/accessor_str.py index c1a2d958c83..e44ef75a88b 100644 --- a/xarray/core/accessor_str.py +++ b/xarray/core/accessor_str.py @@ -847,7 +847,7 @@ def normalize( normalized : same type as values """ - return self._apply(func=lambda x: normalize(form, x)) + return self._apply(func=lambda x: normalize(form, x)) # type: ignore[arg-type] def isalnum(self) -> T_DataArray: """ diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 1f0544c1041..f17bd057c03 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -12,6 +12,7 @@ ) from functools import partial from os import PathLike +from types import EllipsisType from typing import ( TYPE_CHECKING, Any, @@ -2841,7 +2842,7 @@ def stack( dim: Mapping[Any, Sequence[Hashable]] | None = None, create_index: bool | None = True, index_cls: type[Index] = PandasMultiIndex, - **dim_kwargs: Sequence[Hashable], + **dim_kwargs: Sequence[Hashable | EllipsisType], ) -> Self: """ Stack any number of existing dimensions into a single new dimension. diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index e14176f1589..92225df7e19 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -23,6 +23,7 @@ from numbers import Number from operator import methodcaller from os import PathLike +from types import EllipsisType from typing import IO, TYPE_CHECKING, Any, Generic, Literal, cast, overload import numpy as np @@ -5364,10 +5365,10 @@ def _stack_once( @partial(deprecate_dims, old_name="dimensions") def stack( self, - dim: Mapping[Any, Sequence[Hashable | ellipsis]] | None = None, + dim: Mapping[Any, Sequence[Hashable | EllipsisType]] | None = None, create_index: bool | None = True, index_cls: type[Index] = PandasMultiIndex, - **dim_kwargs: Sequence[Hashable | ellipsis], + **dim_kwargs: Sequence[Hashable | EllipsisType], ) -> Self: """ Stack any number of existing dimensions into a single new dimension. diff --git a/xarray/core/datatree.py b/xarray/core/datatree.py index 1b8a5ffbf38..59984c5afa3 100644 --- a/xarray/core/datatree.py +++ b/xarray/core/datatree.py @@ -234,8 +234,7 @@ def __getitem__(self, key: Mapping) -> Dataset: # type: ignore[overload-overlap ... @overload - def __getitem__(self, key: Hashable) -> DataArray: # type: ignore[overload-overlap] - ... + def __getitem__(self, key: Hashable) -> DataArray: ... # See: https://github.com/pydata/xarray/issues/8855 @overload diff --git a/xarray/core/weighted.py b/xarray/core/weighted.py index 8cb90ac1b2b..2c6e7d4282a 100644 --- a/xarray/core/weighted.py +++ b/xarray/core/weighted.py @@ -182,7 +182,7 @@ def _weight_check(w): if is_duck_dask_array(weights.data): # assign to copy - else the check is not triggered weights = weights.copy( - data=weights.data.map_blocks(_weight_check, dtype=weights.dtype), + data=weights.data.map_blocks(_weight_check, dtype=weights.dtype), # type: ignore[call-arg, arg-type] deep=False, ) @@ -264,7 +264,9 @@ def _sum_of_squares( demeaned = da - da.weighted(self.weights).mean(dim=dim) - return self._reduce((demeaned**2), self.weights, dim=dim, skipna=skipna) + # TODO: unsure why mypy complains about these being DataArray return types + # rather than T_DataArray? + return self._reduce((demeaned**2), self.weights, dim=dim, skipna=skipna) # type: ignore[return-value] def _weighted_sum( self, @@ -274,7 +276,7 @@ def _weighted_sum( ) -> T_DataArray: """Reduce a DataArray by a weighted ``sum`` along some dimension(s).""" - return self._reduce(da, self.weights, dim=dim, skipna=skipna) + return self._reduce(da, self.weights, dim=dim, skipna=skipna) # type: ignore[return-value] def _weighted_mean( self, diff --git a/xarray/plot/dataset_plot.py b/xarray/plot/dataset_plot.py index 8ad3b4a6296..e3453b82fdc 100644 --- a/xarray/plot/dataset_plot.py +++ b/xarray/plot/dataset_plot.py @@ -697,7 +697,7 @@ def wrapper(dataset_plotfunc: F) -> F: dataset_plotfunc.__doc__ = ds_doc return dataset_plotfunc - return wrapper + return wrapper # type: ignore[return-value] def _normalize_args( diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index c755924f583..94b90979ac3 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -595,7 +595,7 @@ def test_roundtrip_cftime_datetime_data(self) -> None: assert actual.t.encoding["calendar"] == expected_calendar def test_roundtrip_timedelta_data(self) -> None: - time_deltas = pd.to_timedelta(["1h", "2h", "NaT"]) + time_deltas = pd.to_timedelta(["1h", "2h", "NaT"]) # type: ignore[arg-type, unused-ignore] expected = Dataset({"td": ("td", time_deltas), "td0": time_deltas[0]}) with self.roundtrip(expected) as actual: assert_identical(expected, actual) @@ -2204,7 +2204,7 @@ def create_store(self): store_target, mode="w", **self.version_kwargs ) - def save(self, dataset, store_target, **kwargs): + def save(self, dataset, store_target, **kwargs): # type: ignore[override] return dataset.to_zarr(store=store_target, **kwargs, **self.version_kwargs) @contextlib.contextmanager diff --git a/xarray/tests/test_backends_api.py b/xarray/tests/test_backends_api.py index d4f8b7ed31d..592065f34de 100644 --- a/xarray/tests/test_backends_api.py +++ b/xarray/tests/test_backends_api.py @@ -69,7 +69,7 @@ def open_dataset( class PassThroughBackendEntrypoint(xr.backends.BackendEntrypoint): """Access an object passed to the `open_dataset` method.""" - def open_dataset(self, dataset, *, drop_variables=None): + def open_dataset(self, dataset, *, drop_variables=None): # type: ignore[override] """Return the first argument.""" return dataset diff --git a/xarray/tests/test_coding_times.py b/xarray/tests/test_coding_times.py index 45ae049c08b..5879e6beed8 100644 --- a/xarray/tests/test_coding_times.py +++ b/xarray/tests/test_coding_times.py @@ -628,10 +628,10 @@ def test_cf_timedelta_2d() -> None: @pytest.mark.parametrize( ["deltas", "expected"], [ - (pd.to_timedelta(["1 day", "2 days"]), "days"), - (pd.to_timedelta(["1h", "1 day 1 hour"]), "hours"), - (pd.to_timedelta(["1m", "2m", np.nan]), "minutes"), - (pd.to_timedelta(["1m3s", "1m4s"]), "seconds"), + (pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore] + (pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore] + (pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore] + (pd.to_timedelta(["1 day", "2 days"]), "days"), # type: ignore[arg-type, unused-ignore] ], ) def test_infer_timedelta_units(deltas, expected) -> None: diff --git a/xarray/tests/test_conventions.py b/xarray/tests/test_conventions.py index d7291d6abee..e6c69fc1ee1 100644 --- a/xarray/tests/test_conventions.py +++ b/xarray/tests/test_conventions.py @@ -119,7 +119,7 @@ def test_incompatible_attributes(self) -> None: Variable( ["t"], pd.date_range("2000-01-01", periods=3), {"units": "foobar"} ), - Variable(["t"], pd.to_timedelta(["1 day"]), {"units": "foobar"}), + Variable(["t"], pd.to_timedelta(["1 day"]), {"units": "foobar"}), # type: ignore[arg-type, unused-ignore] Variable(["t"], [0, 1, 2], {"add_offset": 0}, {"add_offset": 2}), Variable(["t"], [0, 1, 2], {"_FillValue": 0}, {"_FillValue": 2}), ] diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index 9feab73d3d1..73bd8584d0b 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -7159,7 +7159,7 @@ def test_result_as_expected(self) -> None: def test_error_on_ellipsis_without_list(self) -> None: da = DataArray([[1, 2], [1, 2]], dims=("x", "y")) with pytest.raises(ValueError): - da.stack(flat=...) + da.stack(flat=...) # type: ignore def test_nD_coord_dataarray() -> None: diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index 9d0eb81bace..34aee38a1e3 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -118,9 +118,9 @@ def test_format_items(self) -> None: np.arange(4) * np.timedelta64(500, "ms"), "00:00:00 00:00:00.500000 00:00:01 00:00:01.500000", ), - (pd.to_timedelta(["NaT", "0s", "1s", "NaT"]), "NaT 00:00:00 00:00:01 NaT"), + (pd.to_timedelta(["NaT", "0s", "1s", "NaT"]), "NaT 00:00:00 00:00:01 NaT"), # type: ignore[arg-type, unused-ignore] ( - pd.to_timedelta(["1 day 1 hour", "1 day", "0 hours"]), + pd.to_timedelta(["1 day 1 hour", "1 day", "0 hours"]), # type: ignore[arg-type, unused-ignore] "1 days 01:00:00 1 days 00:00:00 0 days 00:00:00", ), ([1, 2, 3], "1 2 3"), diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index 3ebaeff712b..ef8d6e9472f 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -224,16 +224,16 @@ def test_label_from_attrs(self) -> None: assert label_from_attrs(da) == long_latex_name def test1d(self) -> None: - self.darray[:, 0, 0].plot() + self.darray[:, 0, 0].plot() # type: ignore[call-arg] with pytest.raises(ValueError, match=r"x must be one of None, 'dim_0'"): - self.darray[:, 0, 0].plot(x="dim_1") + self.darray[:, 0, 0].plot(x="dim_1") # type: ignore[call-arg] with pytest.raises(TypeError, match=r"complex128"): - (self.darray[:, 0, 0] + 1j).plot() + (self.darray[:, 0, 0] + 1j).plot() # type: ignore[call-arg] def test_1d_bool(self) -> None: - xr.ones_like(self.darray[:, 0, 0], dtype=bool).plot() + xr.ones_like(self.darray[:, 0, 0], dtype=bool).plot() # type: ignore[call-arg] def test_1d_x_y_kw(self) -> None: z = np.arange(10) @@ -243,17 +243,17 @@ def test_1d_x_y_kw(self) -> None: f, axs = plt.subplots(3, 1, squeeze=False) for aa, (x, y) in enumerate(xy): - da.plot(x=x, y=y, ax=axs.flat[aa]) + da.plot(x=x, y=y, ax=axs.flat[aa]) # type: ignore[call-arg] with pytest.raises(ValueError, match=r"Cannot specify both"): - da.plot(x="z", y="z") + da.plot(x="z", y="z") # type: ignore[call-arg] error_msg = "must be one of None, 'z'" with pytest.raises(ValueError, match=rf"x {error_msg}"): - da.plot(x="f") + da.plot(x="f") # type: ignore[call-arg] with pytest.raises(ValueError, match=rf"y {error_msg}"): - da.plot(y="f") + da.plot(y="f") # type: ignore[call-arg] def test_multiindex_level_as_coord(self) -> None: da = xr.DataArray( @@ -264,11 +264,11 @@ def test_multiindex_level_as_coord(self) -> None: da = da.set_index(x=["a", "b"]) for x in ["a", "b"]: - h = da.plot(x=x)[0] + h = da.plot(x=x)[0] # type: ignore[call-arg] assert_array_equal(h.get_xdata(), da[x].values) for y in ["a", "b"]: - h = da.plot(y=y)[0] + h = da.plot(y=y)[0] # type: ignore[call-arg] assert_array_equal(h.get_ydata(), da[y].values) # Test for bug in GH issue #2725 @@ -302,10 +302,10 @@ def test_line_plot_along_1d_coord(self) -> None: coords={"x": x_coord, "time": t_coord}, ) - line = da.plot(x="time", hue="x")[0] + line = da.plot(x="time", hue="x")[0] # type: ignore[call-arg] assert_array_equal(line.get_xdata(), da.coords["time"].values) - line = da.plot(y="time", hue="x")[0] + line = da.plot(y="time", hue="x")[0] # type: ignore[call-arg] assert_array_equal(line.get_ydata(), da.coords["time"].values) def test_line_plot_wrong_hue(self) -> None: @@ -315,7 +315,7 @@ def test_line_plot_wrong_hue(self) -> None: ) with pytest.raises(ValueError, match="hue must be one of"): - da.plot(x="t", hue="wrong_coord") + da.plot(x="t", hue="wrong_coord") # type: ignore[call-arg] def test_2d_line(self) -> None: with pytest.raises(ValueError, match=r"hue"): @@ -387,7 +387,7 @@ def test_2d_coord_line_plot_coords_transpose_invariant(self) -> None: def test_2d_before_squeeze(self) -> None: a = DataArray(easy_array((1, 5))) - a.plot() + a.plot() # type: ignore[call-arg] def test2d_uniform_calls_imshow(self) -> None: assert self.imshow_called(self.darray[:, :, 0].plot.imshow) @@ -517,7 +517,7 @@ def test_contourf_cmap_set_with_bad_under_over(self) -> None: assert cmap(np.inf) == cmap_expected(np.inf) def test3d(self) -> None: - self.darray.plot() + self.darray.plot() # type: ignore[call-arg] def test_can_pass_in_axis(self) -> None: self.pass_in_axis(self.darray.plot) @@ -605,10 +605,10 @@ def test_geo_data(self) -> None: dims=("y", "x"), coords={"lon": (("y", "x"), lon), "lat": (("y", "x"), lat)}, ) - da.plot(x="lon", y="lat") + da.plot(x="lon", y="lat") # type: ignore[call-arg] ax = plt.gca() assert ax.has_data() - da.plot(x="lat", y="lon") + da.plot(x="lat", y="lon") # type: ignore[call-arg] ax = plt.gca() assert ax.has_data() @@ -619,7 +619,7 @@ def test_datetime_dimension(self) -> None: a = DataArray( easy_array((nrow, ncol)), coords=[("time", time), ("y", range(ncol))] ) - a.plot() + a.plot() # type: ignore[call-arg] ax = plt.gca() assert ax.has_data() @@ -631,7 +631,7 @@ def test_date_dimension(self) -> None: a = DataArray( easy_array((nrow, ncol)), coords=[("time", time), ("y", range(ncol))] ) - a.plot() + a.plot() # type: ignore[call-arg] ax = plt.gca() assert ax.has_data() @@ -641,24 +641,24 @@ def test_convenient_facetgrid(self) -> None: a = easy_array((10, 15, 4)) d = DataArray(a, dims=["y", "x", "z"]) d.coords["z"] = list("abcd") - g = d.plot(x="x", y="y", col="z", col_wrap=2, cmap="cool") + g = d.plot(x="x", y="y", col="z", col_wrap=2, cmap="cool") # type: ignore[call-arg] assert_array_equal(g.axs.shape, [2, 2]) for ax in g.axs.flat: assert ax.has_data() with pytest.raises(ValueError, match=r"[Ff]acet"): - d.plot(x="x", y="y", col="z", ax=plt.gca()) + d.plot(x="x", y="y", col="z", ax=plt.gca()) # type: ignore[call-arg] with pytest.raises(ValueError, match=r"[Ff]acet"): - d[0].plot(x="x", y="y", col="z", ax=plt.gca()) + d[0].plot(x="x", y="y", col="z", ax=plt.gca()) # type: ignore[call-arg] @pytest.mark.slow def test_subplot_kws(self) -> None: a = easy_array((10, 15, 4)) d = DataArray(a, dims=["y", "x", "z"]) d.coords["z"] = list("abcd") - g = d.plot( + g = d.plot( # type: ignore[call-arg] x="x", y="y", col="z", @@ -672,58 +672,58 @@ def test_subplot_kws(self) -> None: @pytest.mark.slow def test_plot_size(self) -> None: - self.darray[:, 0, 0].plot(figsize=(13, 5)) + self.darray[:, 0, 0].plot(figsize=(13, 5)) # type: ignore[call-arg] assert tuple(plt.gcf().get_size_inches()) == (13, 5) - self.darray.plot(figsize=(13, 5)) + self.darray.plot(figsize=(13, 5)) # type: ignore[call-arg] assert tuple(plt.gcf().get_size_inches()) == (13, 5) - self.darray.plot(size=5) + self.darray.plot(size=5) # type: ignore[call-arg] assert plt.gcf().get_size_inches()[1] == 5 - self.darray.plot(size=5, aspect=2) + self.darray.plot(size=5, aspect=2) # type: ignore[call-arg] assert tuple(plt.gcf().get_size_inches()) == (10, 5) with pytest.raises(ValueError, match=r"cannot provide both"): - self.darray.plot(ax=plt.gca(), figsize=(3, 4)) + self.darray.plot(ax=plt.gca(), figsize=(3, 4)) # type: ignore[call-arg] with pytest.raises(ValueError, match=r"cannot provide both"): - self.darray.plot(size=5, figsize=(3, 4)) + self.darray.plot(size=5, figsize=(3, 4)) # type: ignore[call-arg] with pytest.raises(ValueError, match=r"cannot provide both"): - self.darray.plot(size=5, ax=plt.gca()) + self.darray.plot(size=5, ax=plt.gca()) # type: ignore[call-arg] with pytest.raises(ValueError, match=r"cannot provide `aspect`"): - self.darray.plot(aspect=1) + self.darray.plot(aspect=1) # type: ignore[call-arg] @pytest.mark.slow @pytest.mark.filterwarnings("ignore:tight_layout cannot") def test_convenient_facetgrid_4d(self) -> None: a = easy_array((10, 15, 2, 3)) d = DataArray(a, dims=["y", "x", "columns", "rows"]) - g = d.plot(x="x", y="y", col="columns", row="rows") + g = d.plot(x="x", y="y", col="columns", row="rows") # type: ignore[call-arg] assert_array_equal(g.axs.shape, [3, 2]) for ax in g.axs.flat: assert ax.has_data() with pytest.raises(ValueError, match=r"[Ff]acet"): - d.plot(x="x", y="y", col="columns", ax=plt.gca()) + d.plot(x="x", y="y", col="columns", ax=plt.gca()) # type: ignore[call-arg] def test_coord_with_interval(self) -> None: """Test line plot with intervals.""" bins = [-1, 0, 1, 2] - self.darray.groupby_bins("dim_0", bins).mean(...).plot() + self.darray.groupby_bins("dim_0", bins).mean(...).plot() # type: ignore[call-arg] def test_coord_with_interval_x(self) -> None: """Test line plot with intervals explicitly on x axis.""" bins = [-1, 0, 1, 2] - self.darray.groupby_bins("dim_0", bins).mean(...).plot(x="dim_0_bins") + self.darray.groupby_bins("dim_0", bins).mean(...).plot(x="dim_0_bins") # type: ignore[call-arg] def test_coord_with_interval_y(self) -> None: """Test line plot with intervals explicitly on y axis.""" bins = [-1, 0, 1, 2] - self.darray.groupby_bins("dim_0", bins).mean(...).plot(y="dim_0_bins") + self.darray.groupby_bins("dim_0", bins).mean(...).plot(y="dim_0_bins") # type: ignore[call-arg] def test_coord_with_interval_xy(self) -> None: """Test line plot with intervals on both x and y axes.""" @@ -737,7 +737,7 @@ def test_labels_with_units_with_interval(self, dim) -> None: arr = self.darray.groupby_bins("dim_0", bins).mean(...) arr.dim_0_bins.attrs["units"] = "m" - (mappable,) = arr.plot(**{dim: "dim_0_bins"}) + (mappable,) = arr.plot(**{dim: "dim_0_bins"}) # type: ignore[arg-type] ax = mappable.figure.gca() actual = getattr(ax, f"get_{dim}label")() @@ -747,9 +747,9 @@ def test_labels_with_units_with_interval(self, dim) -> None: def test_multiplot_over_length_one_dim(self) -> None: a = easy_array((3, 1, 1, 1)) d = DataArray(a, dims=("x", "col", "row", "hue")) - d.plot(col="col") - d.plot(row="row") - d.plot(hue="hue") + d.plot(col="col") # type: ignore[call-arg] + d.plot(row="row") # type: ignore[call-arg] + d.plot(hue="hue") # type: ignore[call-arg] class TestPlot1D(PlotTestCase): @@ -760,27 +760,27 @@ def setUp(self) -> None: self.darray.period.attrs["units"] = "s" def test_xlabel_is_index_name(self) -> None: - self.darray.plot() + self.darray.plot() # type: ignore[call-arg] assert "period [s]" == plt.gca().get_xlabel() def test_no_label_name_on_x_axis(self) -> None: - self.darray.plot(y="period") + self.darray.plot(y="period") # type: ignore[call-arg] assert "" == plt.gca().get_xlabel() def test_no_label_name_on_y_axis(self) -> None: - self.darray.plot() + self.darray.plot() # type: ignore[call-arg] assert "" == plt.gca().get_ylabel() def test_ylabel_is_data_name(self) -> None: self.darray.name = "temperature" self.darray.attrs["units"] = "degrees_Celsius" - self.darray.plot() + self.darray.plot() # type: ignore[call-arg] assert "temperature [degrees_Celsius]" == plt.gca().get_ylabel() def test_xlabel_is_data_name(self) -> None: self.darray.name = "temperature" self.darray.attrs["units"] = "degrees_Celsius" - self.darray.plot(y="period") + self.darray.plot(y="period") # type: ignore[call-arg] assert "temperature [degrees_Celsius]" == plt.gca().get_xlabel() def test_format_string(self) -> None: @@ -859,12 +859,12 @@ def test_step_with_hue_and_where(self, where) -> None: assert hdl[0].get_drawstyle() == f"steps-{where}" def test_drawstyle_steps(self) -> None: - hdl = self.darray[0].plot(hue="dim_2", drawstyle="steps") + hdl = self.darray[0].plot(hue="dim_2", drawstyle="steps") # type: ignore[call-arg] assert hdl[0].get_drawstyle() == "steps" @pytest.mark.parametrize("where", ["pre", "post", "mid"]) def test_drawstyle_steps_with_where(self, where) -> None: - hdl = self.darray[0].plot(hue="dim_2", drawstyle=f"steps-{where}") + hdl = self.darray[0].plot(hue="dim_2", drawstyle=f"steps-{where}") # type: ignore[call-arg] assert hdl[0].get_drawstyle() == f"steps-{where}" def test_coord_with_interval_step(self) -> None: @@ -907,29 +907,29 @@ def setUp(self) -> None: self.darray = DataArray(easy_array((2, 3, 4))) def test_3d_array(self) -> None: - self.darray.plot.hist() + self.darray.plot.hist() # type: ignore[call-arg] def test_xlabel_uses_name(self) -> None: self.darray.name = "testpoints" self.darray.attrs["units"] = "testunits" - self.darray.plot.hist() + self.darray.plot.hist() # type: ignore[call-arg] assert "testpoints [testunits]" == plt.gca().get_xlabel() def test_title_is_histogram(self) -> None: self.darray.coords["d"] = 10 - self.darray.plot.hist() + self.darray.plot.hist() # type: ignore[call-arg] assert "d = 10" == plt.gca().get_title() def test_can_pass_in_kwargs(self) -> None: nbins = 5 - self.darray.plot.hist(bins=nbins) + self.darray.plot.hist(bins=nbins) # type: ignore[call-arg] assert nbins == len(plt.gca().patches) def test_can_pass_in_axis(self) -> None: self.pass_in_axis(self.darray.plot.hist) def test_primitive_returned(self) -> None: - n, bins, patches = self.darray.plot.hist() + n, bins, patches = self.darray.plot.hist() # type: ignore[call-arg] assert isinstance(n, np.ndarray) assert isinstance(bins, np.ndarray) assert isinstance(patches, mpl.container.BarContainer) @@ -938,11 +938,11 @@ def test_primitive_returned(self) -> None: @pytest.mark.slow def test_plot_nans(self) -> None: self.darray[0, 0, 0] = np.nan - self.darray.plot.hist() + self.darray.plot.hist() # type: ignore[call-arg] def test_hist_coord_with_interval(self) -> None: ( - self.darray.groupby_bins("dim_0", [-1, 0, 1, 2]) + self.darray.groupby_bins("dim_0", [-1, 0, 1, 2]) # type: ignore[call-arg] .mean(...) .plot.hist(range=(-1, 2)) ) @@ -1246,7 +1246,7 @@ def test_discrete_colormap_int_levels(self) -> None: def test_discrete_colormap_list_levels_and_vmin_or_vmax(self) -> None: levels = [0, 5, 10, 15] - primitive = self.darray.plot(levels=levels, vmin=-3, vmax=20) + primitive = self.darray.plot(levels=levels, vmin=-3, vmax=20) # type: ignore[call-arg] assert primitive.norm.vmax == max(levels) assert primitive.norm.vmin == min(levels) @@ -1316,11 +1316,11 @@ def test_1d_raises_valueerror(self) -> None: self.plotfunc(self.darray[0, :]) def test_bool(self) -> None: - xr.ones_like(self.darray, dtype=bool).plot() + xr.ones_like(self.darray, dtype=bool).plot() # type: ignore[call-arg] def test_complex_raises_typeerror(self) -> None: with pytest.raises(TypeError, match=r"complex128"): - (self.darray + 1j).plot() + (self.darray + 1j).plot() # type: ignore[call-arg] def test_3d_raises_valueerror(self) -> None: a = DataArray(easy_array((2, 3, 4))) @@ -1720,10 +1720,10 @@ def test_colormap_error_norm_and_vmin_vmax(self) -> None: norm = mpl.colors.LogNorm(0.1, 1e1) with pytest.raises(ValueError): - self.darray.plot(norm=norm, vmin=2) + self.darray.plot(norm=norm, vmin=2) # type: ignore[call-arg] with pytest.raises(ValueError): - self.darray.plot(norm=norm, vmax=2) + self.darray.plot(norm=norm, vmax=2) # type: ignore[call-arg] @pytest.mark.slow @@ -2516,10 +2516,10 @@ def setUp(self) -> None: self.darray.row.attrs["units"] = "rowunits" def test_facetgrid_shape(self) -> None: - g = self.darray.plot(row="row", col="col", hue="hue") + g = self.darray.plot(row="row", col="col", hue="hue") # type: ignore[call-arg] assert g.axs.shape == (len(self.darray.row), len(self.darray.col)) - g = self.darray.plot(row="col", col="row", hue="hue") + g = self.darray.plot(row="col", col="row", hue="hue") # type: ignore[call-arg] assert g.axs.shape == (len(self.darray.col), len(self.darray.row)) def test_unnamed_args(self) -> None: @@ -2532,7 +2532,7 @@ def test_unnamed_args(self) -> None: assert lines[0].get_linestyle() == "--" def test_default_labels(self) -> None: - g = self.darray.plot(row="row", col="col", hue="hue") + g = self.darray.plot(row="row", col="col", hue="hue") # type: ignore[call-arg] # Rightmost column should be labeled for label, ax in zip(self.darray.coords["row"].values, g.axs[:, -1]): assert substring_in_axes(label, ax) @@ -2547,7 +2547,7 @@ def test_default_labels(self) -> None: def test_test_empty_cell(self) -> None: g = ( - self.darray.isel(row=1) + self.darray.isel(row=1) # type: ignore[call-arg] .drop_vars("row") .plot(col="col", hue="hue", col_wrap=2) ) @@ -2556,7 +2556,7 @@ def test_test_empty_cell(self) -> None: assert not bottomright.get_visible() def test_set_axis_labels(self) -> None: - g = self.darray.plot(row="row", col="col", hue="hue") + g = self.darray.plot(row="row", col="col", hue="hue") # type: ignore[call-arg] g.set_axis_labels("longitude", "latitude") alltxt = text_in_fig() @@ -2573,7 +2573,7 @@ def test_figsize_and_size(self) -> None: def test_wrong_num_of_dimensions(self) -> None: with pytest.raises(ValueError): - self.darray.plot(row="row", hue="hue") + self.darray.plot(row="row", hue="hue") # type: ignore[call-arg] self.darray.plot.line(row="row", hue="hue") @@ -3379,14 +3379,14 @@ def test_plot1d_default_rcparams() -> None: fig, ax = plt.subplots(1, 1) ds.plot.scatter(x="A", y="B", marker="o", ax=ax) actual: np.ndarray = mpl.colors.to_rgba_array("w") - expected: np.ndarray = ax.collections[0].get_edgecolor() # type: ignore[assignment] # mpl error? + expected: np.ndarray = ax.collections[0].get_edgecolor() # type: ignore[assignment] np.testing.assert_allclose(actual, expected) # Facetgrids should have the default value as well: fg = ds.plot.scatter(x="A", y="B", col="x", marker="o") ax = fg.axs.ravel()[0] actual = mpl.colors.to_rgba_array("w") - expected = ax.collections[0].get_edgecolor() # type: ignore[assignment] # mpl error? + expected = ax.collections[0].get_edgecolor() # type: ignore[assignment] np.testing.assert_allclose(actual, expected) # scatter should not emit any warnings when using unfilled markers: @@ -3398,7 +3398,7 @@ def test_plot1d_default_rcparams() -> None: fig, ax = plt.subplots(1, 1) ds.plot.scatter(x="A", y="B", marker="o", ax=ax, edgecolor="k") actual = mpl.colors.to_rgba_array("k") - expected = ax.collections[0].get_edgecolor() # type: ignore[assignment] # mpl error? + expected = ax.collections[0].get_edgecolor() # type: ignore[assignment] np.testing.assert_allclose(actual, expected) @@ -3422,7 +3422,7 @@ def test_9155() -> None: with figure_context(): data = xr.DataArray([1, 2, 3], dims=["x"]) fig, ax = plt.subplots(ncols=1, nrows=1) - data.plot(ax=ax) + data.plot(ax=ax) # type: ignore[call-arg] @requires_matplotlib diff --git a/xarray/tests/test_plugins.py b/xarray/tests/test_plugins.py index a0d742c3159..2b321ba8dfc 100644 --- a/xarray/tests/test_plugins.py +++ b/xarray/tests/test_plugins.py @@ -21,22 +21,22 @@ class DummyBackendEntrypointArgs(common.BackendEntrypoint): - def open_dataset(filename_or_obj, *args): + def open_dataset(filename_or_obj, *args): # type: ignore[override] pass class DummyBackendEntrypointKwargs(common.BackendEntrypoint): - def open_dataset(filename_or_obj, **kwargs): + def open_dataset(filename_or_obj, **kwargs): # type: ignore[override] pass class DummyBackendEntrypoint1(common.BackendEntrypoint): - def open_dataset(self, filename_or_obj, *, decoder): + def open_dataset(self, filename_or_obj, *, decoder): # type: ignore[override] pass class DummyBackendEntrypoint2(common.BackendEntrypoint): - def open_dataset(self, filename_or_obj, *, decoder): + def open_dataset(self, filename_or_obj, *, decoder): # type: ignore[override] pass