Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ Documentation
Internal Changes
~~~~~~~~~~~~~~~~

- Replace ``distutils.version`` with ``packaging.version`` (:issue:`6092`).
By `Mathias Hauser <https://github.com/mathause>`_.


.. _whats-new.0.20.2:

Expand Down
10 changes: 5 additions & 5 deletions xarray/backends/h5netcdf_.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import functools
import io
import os
from distutils.version import LooseVersion

import numpy as np
from packaging.version import Version

from ..core import indexing
from ..core.utils import (
Expand Down Expand Up @@ -156,16 +156,16 @@ def open(

kwargs = {"invalid_netcdf": invalid_netcdf}
if phony_dims is not None:
if LooseVersion(h5netcdf.__version__) >= LooseVersion("0.8.0"):
if Version(h5netcdf.__version__) >= Version("0.8.0"):
kwargs["phony_dims"] = phony_dims
else:
raise ValueError(
"h5netcdf backend keyword argument 'phony_dims' needs "
"h5netcdf >= 0.8.0."
)
if LooseVersion(h5netcdf.__version__) >= LooseVersion(
"0.10.0"
) and LooseVersion(h5netcdf.core.h5py.__version__) >= LooseVersion("3.0.0"):
if Version(h5netcdf.__version__) >= Version("0.10.0") and Version(
h5netcdf.core.h5py.__version__
) >= Version("3.0.0"):
kwargs["decode_vlen_strings"] = decode_vlen_strings

if lock is None:
Expand Down
12 changes: 5 additions & 7 deletions xarray/coding/cftimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@
import re
import warnings
from datetime import timedelta
from distutils.version import LooseVersion
from typing import Tuple, Type

import numpy as np
import pandas as pd
from packaging.version import Version

from xarray.core.utils import is_scalar

Expand Down Expand Up @@ -193,15 +193,13 @@ def f(self, min_cftime_version=min_cftime_version):
if cftime is None:
raise ModuleNotFoundError("No module named 'cftime'")

version = cftime.__version__

if LooseVersion(version) >= LooseVersion(min_cftime_version):
if Version(cftime.__version__) >= Version(min_cftime_version):
return get_date_field(self._data, name)
else:
raise ImportError(
"The {!r} accessor requires a minimum "
"version of cftime of {}. Found an "
"installed version of {}.".format(name, min_cftime_version, version)
f"The {name:!r} accessor requires a minimum "
f"version of cftime of {min_cftime_version}. Found an "
f"installed version of {cftime.__version__}."
)

f.__name__ = name
Expand Down
7 changes: 4 additions & 3 deletions xarray/core/dask_array_compat.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import warnings

import numpy as np
from packaging.version import Version

from .pycompat import dask_version

Expand Down Expand Up @@ -56,7 +57,7 @@ def pad(array, pad_width, mode="constant", **kwargs):
return padded


if dask_version > "2.30.0":
if dask_version > Version("2.30.0"):
ensure_minimum_chunksize = da.overlap.ensure_minimum_chunksize
else:

Expand Down Expand Up @@ -113,7 +114,7 @@ def ensure_minimum_chunksize(size, chunks):
return tuple(output)


if dask_version > "2021.03.0":
if dask_version > Version("2021.03.0"):
sliding_window_view = da.lib.stride_tricks.sliding_window_view
else:

Expand Down Expand Up @@ -179,7 +180,7 @@ def sliding_window_view(x, window_shape, axis=None):
axis=axis,
)
# map_overlap's signature changed in https://github.com/dask/dask/pull/6165
if dask_version > "2.18.0":
if dask_version > Version("2.18.0"):
return map_overlap(_np_sliding_window_view, x, align_arrays=False, **kwargs)
else:
return map_overlap(x, _np_sliding_window_view, **kwargs)
3 changes: 2 additions & 1 deletion xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from numpy import stack as _stack
from numpy import take, tensordot, transpose, unravel_index # noqa
from numpy import where as _where
from packaging.version import Version

from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils
from .nputils import nanfirst, nanlast
Expand Down Expand Up @@ -175,7 +176,7 @@ def cumulative_trapezoid(y, x, axis):
def astype(data, dtype, **kwargs):
if (
isinstance(data, sparse_array_type)
and sparse_version < "0.11.0"
and sparse_version < Version("0.11.0")
and "casting" in kwargs
):
warnings.warn(
Expand Down
3 changes: 2 additions & 1 deletion xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import numpy as np
import pandas as pd
from packaging.version import Version

from . import duck_array_ops, nputils, utils
from .npcompat import DTypeLike
Expand Down Expand Up @@ -1234,7 +1235,7 @@ def __getitem__(self, key):
return value

def __setitem__(self, key, value):
if dask_version >= "2021.04.1":
if dask_version >= Version("2021.04.1"):
if isinstance(key, BasicIndexer):
self.array[key.tuple] = value
elif isinstance(key, VectorizedIndexer):
Expand Down
3 changes: 2 additions & 1 deletion xarray/core/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import numpy as np
import pandas as pd
from packaging.version import Version

from . import utils
from .common import _contains_datetime_like_objects, ones_like
Expand Down Expand Up @@ -741,7 +742,7 @@ def interp_func(var, x, new_x, method, kwargs):
else:
dtype = var.dtype

if dask_version < "2020.12":
if dask_version < Version("2020.12"):
# Using meta and dtype at the same time doesn't work.
# Remove this whenever the minimum requirement for dask is 2020.12:
meta = None
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/npcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
from distutils.version import LooseVersion
from typing import TYPE_CHECKING, Any, Sequence, TypeVar, Union

import numpy as np
from packaging.version import Version

# Type annotations stubs
try:
Expand Down Expand Up @@ -79,7 +79,7 @@ def __array__(self) -> np.ndarray:
DTypeLike = Union[np.dtype, str] # type: ignore[misc]


if LooseVersion(np.__version__) >= "1.20.0":
if Version(np.__version__) >= Version("1.20.0"):
sliding_window_view = np.lib.stride_tricks.sliding_window_view
else:
from numpy.core.numeric import normalize_axis_tuple # type: ignore[attr-defined]
Expand Down
5 changes: 2 additions & 3 deletions xarray/core/pdcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,11 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from distutils.version import LooseVersion

import pandas as pd
from packaging.version import Version

# allow ourselves to type checks for Panel even after it's removed
if LooseVersion(pd.__version__) < "0.25.0":
if Version(pd.__version__) < Version("0.25.0"):
Panel = pd.Panel
else:

Expand Down
6 changes: 3 additions & 3 deletions xarray/core/pycompat.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from distutils.version import LooseVersion
from importlib import import_module

import numpy as np
from packaging.version import Version

from .utils import is_duck_array

Expand All @@ -19,7 +19,7 @@ class DuckArrayModule:
def __init__(self, mod):
try:
duck_array_module = import_module(mod)
duck_array_version = LooseVersion(duck_array_module.__version__)
duck_array_version = Version(duck_array_module.__version__)

if mod == "dask":
duck_array_type = (import_module("dask.array").Array,)
Expand All @@ -34,7 +34,7 @@ def __init__(self, mod):

except ImportError: # pragma: no cover
duck_array_module = None
duck_array_version = LooseVersion("0.0.0")
duck_array_version = Version("0.0.0")
duck_array_type = ()

self.module = duck_array_module
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/rolling_exp.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from __future__ import annotations

from distutils.version import LooseVersion
from typing import Any, Generic, Mapping, Union

import numpy as np
from packaging.version import Version

from .options import _get_keep_attrs
from .pdcompat import count_not_none
Expand Down Expand Up @@ -37,7 +37,7 @@ def move_exp_nansum(array, *, axis, alpha):
import numbagg

# numbagg <= 0.2.0 did not have a __version__ attribute
if LooseVersion(getattr(numbagg, "__version__", "0.1.0")) < LooseVersion("0.2.0"):
if Version(getattr(numbagg, "__version__", "0.1.0")) < Version("0.2.0"):
raise ValueError("`rolling_exp(...).sum() requires numbagg>=0.2.1.")

return numbagg.move_exp_nansum(array, axis=axis, alpha=alpha)
Expand Down
6 changes: 3 additions & 3 deletions xarray/plot/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
Dataset.plot._____
"""
import functools
from distutils.version import LooseVersion

import numpy as np
import pandas as pd
from packaging.version import Version

from ..core.alignment import broadcast
from .facetgrid import _easy_facetgrid
Expand Down Expand Up @@ -714,7 +714,7 @@ def scatter(
ax = get_axis(figsize, size, aspect, ax, **subplot_kws)
# Using 30, 30 minimizes rotation of the plot. Making it easier to
# build on your intuition from 2D plots:
if LooseVersion(plt.matplotlib.__version__) < "3.5.0":
if Version(plt.matplotlib.__version__) < Version("3.5.0"):
ax.view_init(azim=30, elev=30)
else:
# https://github.com/matplotlib/matplotlib/pull/19873
Expand Down Expand Up @@ -768,7 +768,7 @@ def scatter(
if _data["size"] is not None:
kwargs.update(s=_data["size"].values.ravel())

if LooseVersion(plt.matplotlib.__version__) < "3.5.0":
if Version(plt.matplotlib.__version__) < Version("3.5.0"):
# Plot the data. 3d plots has the z value in upward direction
# instead of y. To make jumping between 2d and 3d easy and intuitive
# switch the order so that z is shown in the depthwise direction:
Expand Down
11 changes: 2 additions & 9 deletions xarray/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
import platform
import warnings
from contextlib import contextmanager
from distutils import version
from unittest import mock # noqa: F401

import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_array_equal # noqa: F401
from packaging.version import Version
from pandas.testing import assert_frame_equal # noqa: F401

import xarray.testing
Expand Down Expand Up @@ -45,21 +45,14 @@ def _importorskip(modname, minversion=None):
mod = importlib.import_module(modname)
has = True
if minversion is not None:
if LooseVersion(mod.__version__) < LooseVersion(minversion):
if Version(mod.__version__) < Version(minversion):
raise ImportError("Minimum version not satisfied")
except ImportError:
has = False
func = pytest.mark.skipif(not has, reason=f"requires {modname}")
return has, func


def LooseVersion(vstring):
# Our development version is something like '0.10.9+aac7bfc'
# This function just ignored the git commit id.
vstring = vstring.split("+")[0]
return version.LooseVersion(vstring)


has_matplotlib, requires_matplotlib = _importorskip("matplotlib")
has_scipy, requires_scipy = _importorskip("scipy")
has_pydap, requires_pydap = _importorskip("pydap.client")
Expand Down
2 changes: 0 additions & 2 deletions xarray/tests/test_accessor_dt.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from distutils.version import LooseVersion

import numpy as np
import pandas as pd
import pytest
Expand Down
15 changes: 8 additions & 7 deletions xarray/tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import numpy as np
import pandas as pd
import pytest
from packaging.version import Version
from pandas.errors import OutOfBoundsDatetime

import xarray as xr
Expand Down Expand Up @@ -45,7 +46,7 @@
from xarray.core import indexing
from xarray.core.options import set_options
from xarray.core.pycompat import dask_array_type
from xarray.tests import LooseVersion, mock
from xarray.tests import mock

from . import (
arm_xfail,
Expand Down Expand Up @@ -2833,9 +2834,9 @@ def test_open_dataset_group(self):
v[...] = 42

kwargs = {}
if LooseVersion(h5netcdf.__version__) >= LooseVersion(
"0.10.0"
) and LooseVersion(h5netcdf.core.h5py.__version__) >= LooseVersion("3.0.0"):
if Version(h5netcdf.__version__) >= Version("0.10.0") and Version(
h5netcdf.core.h5py.__version__
) >= Version("3.0.0"):
kwargs = dict(decode_vlen_strings=True)

h5 = h5netcdf.File(tmp_file, mode="r", **kwargs)
Expand All @@ -2860,9 +2861,9 @@ def test_deepcopy(self):
v[:] = np.arange(10)

kwargs = {}
if LooseVersion(h5netcdf.__version__) >= LooseVersion(
"0.10.0"
) and LooseVersion(h5netcdf.core.h5py.__version__) >= LooseVersion("3.0.0"):
if Version(h5netcdf.__version__) >= Version("0.10.0") and Version(
h5netcdf.core.h5py.__version__
) >= Version("3.0.0"):
kwargs = dict(decode_vlen_strings=True)

h5 = h5netcdf.File(tmp_file, mode="r", **kwargs)
Expand Down
Loading