diff --git a/.pep8speaks.yml b/.pep8speaks.yml index 018003f2223..8d87864e426 100644 --- a/.pep8speaks.yml +++ b/.pep8speaks.yml @@ -1,16 +1,6 @@ -# File : .pep8speaks.yml - -# This should be kept in sync with the duplicate config in the [pycodestyle] -# block of setup.cfg. +# https://github.com/OrkoHunter/pep8speaks for more info +# pep8speaks will use the flake8 configs in `setup.cfg` scanner: - diff_only: False # If True, errors caused by only the patch are shown - -pycodestyle: - max-line-length: 79 - ignore: # Errors and warnings to ignore - - E402 # module level import not at top of file - - E731 # do not assign a lambda expression, use a def - - E741 # ambiguous variable name - - W503 # line break before binary operator - - W504 # line break after binary operator + diff_only: False + linter: flake8 diff --git a/.travis.yml b/.travis.yml index f351310459b..913c5e1c0f7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -60,7 +60,7 @@ script: cd doc; sphinx-build -n -j auto -b html -d _build/doctrees . _build/html; elif [[ "$CONDA_ENV" == "lint" ]]; then - pycodestyle xarray ; + flake8 ; elif [[ "$CONDA_ENV" == "py36-hypothesis" ]]; then pytest properties ; else diff --git a/asv_bench/benchmarks/__init__.py b/asv_bench/benchmarks/__init__.py index 997fdfd0db0..d0eb6282fce 100644 --- a/asv_bench/benchmarks/__init__.py +++ b/asv_bench/benchmarks/__init__.py @@ -1,6 +1,5 @@ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function +from __future__ import absolute_import, division, print_function + import itertools import numpy as np diff --git a/ci/requirements-py36.yml b/ci/requirements-py36.yml index d6dafd8d540..aab926ac6aa 100644 --- a/ci/requirements-py36.yml +++ b/ci/requirements-py36.yml @@ -14,7 +14,7 @@ dependencies: - pytest-cov - pytest-env - coveralls - - pycodestyle + - flake8 - numpy>=1.12 - pandas>=0.19 - scipy diff --git a/ci/requirements-py37.yml b/ci/requirements-py37.yml index c5f5d71b8e5..fe5afd589c8 100644 --- a/ci/requirements-py37.yml +++ b/ci/requirements-py37.yml @@ -15,7 +15,7 @@ dependencies: - pytest-cov - pytest-env - coveralls - - pycodestyle + - flake8 - numpy>=1.12 - pandas>=0.19 - scipy diff --git a/doc/conf.py b/doc/conf.py index 322741556b6..237669460b2 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -13,11 +13,11 @@ # serve to show the default. from __future__ import absolute_import, division, print_function -from contextlib import suppress import datetime import os import subprocess import sys +from contextlib import suppress import xarray diff --git a/doc/contributing.rst b/doc/contributing.rst index fba09497abe..651c1d47db5 100644 --- a/doc/contributing.rst +++ b/doc/contributing.rst @@ -351,11 +351,11 @@ the more common ``PEP8`` issues: - passing arguments should have spaces after commas, e.g. ``foo(arg1, arg2, kw1='bar')`` :ref:`Continuous Integration ` will run -the `pycodestyle `_ tool +the `flake8 `_ tool and report any stylistic errors in your code. Therefore, it is helpful before -submitting code to run the check yourself:: +submitting code to run the check yourself: - pycodestyle xarray + flake8 Other recommended but optional tools for checking code quality (not currently enforced in CI): @@ -363,8 +363,6 @@ enforced in CI): - `mypy `_ performs static type checking, which can make it easier to catch bugs. Please run ``mypy xarray`` if you annotate any code with `type hints `_. -- `flake8 `_ includes a few more automated - checks than those enforced by pycodestyle. - `isort `_ will highlight incorrectly sorted imports. ``isort -y`` will automatically fix them. See also `flake8-isort `_. diff --git a/doc/examples/_code/weather_data_setup.py b/doc/examples/_code/weather_data_setup.py index 89470542d5a..d3a3e2d065a 100644 --- a/doc/examples/_code/weather_data_setup.py +++ b/doc/examples/_code/weather_data_setup.py @@ -1,6 +1,6 @@ import numpy as np import pandas as pd -import seaborn as sns # pandas aware plotting library +import seaborn as sns # noqa, pandas aware plotting library import xarray as xr diff --git a/setup.cfg b/setup.cfg index 18922b1647a..51449138780 100644 --- a/setup.cfg +++ b/setup.cfg @@ -11,9 +11,18 @@ env = UVCDAT_ANONYMOUS_LOG=no # This should be kept in sync with .pep8speaks.yml -[pycodestyle] +[flake8] max-line-length=79 -ignore=E402,E731,E741,W503,W504 +ignore= + E402 + E731 + E741 + W503 + W504 + # Unused imports; TODO: Allow typing to work without triggering errors + F401 +exclude= + doc [isort] default_section=THIRDPARTY diff --git a/xarray/__init__.py b/xarray/__init__.py index 506cb46de26..9eaa705e108 100644 --- a/xarray/__init__.py +++ b/xarray/__init__.py @@ -1,3 +1,4 @@ +""" isort:skip_file """ # flake8: noqa from ._version import get_versions diff --git a/xarray/backends/__init__.py b/xarray/backends/__init__.py index 9b9e04d9346..292a6d68523 100644 --- a/xarray/backends/__init__.py +++ b/xarray/backends/__init__.py @@ -3,16 +3,16 @@ DataStores provide a uniform interface for saving and loading data in different formats. They should not be used directly, but rather through Dataset objects. """ -from .common import AbstractDataStore -from .file_manager import FileManager, CachingFileManager, DummyFileManager from .cfgrib_ import CfGribDataStore +from .common import AbstractDataStore +from .file_manager import CachingFileManager, DummyFileManager, FileManager +from .h5netcdf_ import H5NetCDFStore from .memory import InMemoryDataStore from .netCDF4_ import NetCDF4DataStore +from .pseudonetcdf_ import PseudoNetCDFDataStore from .pydap_ import PydapDataStore from .pynio_ import NioDataStore from .scipy_ import ScipyDataStore -from .h5netcdf_ import H5NetCDFStore -from .pseudonetcdf_ import PseudoNetCDFDataStore from .zarr import ZarrStore __all__ = [ diff --git a/xarray/backends/file_manager.py b/xarray/backends/file_manager.py index 5955ef54d6e..0d11632fa67 100644 --- a/xarray/backends/file_manager.py +++ b/xarray/backends/file_manager.py @@ -1,7 +1,7 @@ import contextlib import threading -from typing import Any, Dict import warnings +from typing import Any, Dict from ..core import utils from ..core.options import OPTIONS diff --git a/xarray/backends/locks.py b/xarray/backends/locks.py index 65150562538..bb63186ce3a 100644 --- a/xarray/backends/locks.py +++ b/xarray/backends/locks.py @@ -1,7 +1,7 @@ import multiprocessing import threading -from typing import Any, MutableMapping import weakref +from typing import Any, MutableMapping try: from dask.utils import SerializableLock diff --git a/xarray/backends/netCDF4_.py b/xarray/backends/netCDF4_.py index 2396523dca7..268afcfcea5 100644 --- a/xarray/backends/netCDF4_.py +++ b/xarray/backends/netCDF4_.py @@ -174,7 +174,7 @@ def _force_native_endianness(var): # if endian exists, remove it from the encoding. var.encoding.pop('endian', None) # check to see if encoding has a value for endian its 'native' - if not var.encoding.get('endian', 'native') is 'native': + if not var.encoding.get('endian', 'native') == 'native': raise NotImplementedError("Attempt to write non-native endian type, " "this is not supported by the netCDF4 " "python library.") @@ -237,6 +237,7 @@ def _extract_nc4_variable_encoding(variable, raise_on_invalid=False, class GroupWrapper: """Wrap netCDF4.Group objects so closing them closes the root group.""" + def __init__(self, value): self.value = value diff --git a/xarray/coding/variables.py b/xarray/coding/variables.py index ae8b97c7352..8f5ffe8a38a 100644 --- a/xarray/coding/variables.py +++ b/xarray/coding/variables.py @@ -1,7 +1,7 @@ """Coders for individual Variable objects.""" -from typing import Any import warnings from functools import partial +from typing import Any import numpy as np import pandas as pd diff --git a/xarray/core/accessor_str.py b/xarray/core/accessor_str.py index 564593a032e..4a1983517eb 100644 --- a/xarray/core/accessor_str.py +++ b/xarray/core/accessor_str.py @@ -45,7 +45,6 @@ from .computation import apply_ufunc - _cpython_optimized_encoders = ( "utf-8", "utf8", "latin-1", "latin1", "iso-8859-1", "mbcs", "ascii" ) diff --git a/xarray/core/alignment.py b/xarray/core/alignment.py index 295f69a2afc..031861b0ccf 100644 --- a/xarray/core/alignment.py +++ b/xarray/core/alignment.py @@ -8,7 +8,7 @@ import numpy as np import pandas as pd -from . import utils, dtypes +from . import dtypes, utils from .indexing import get_indexer_nd from .utils import is_dict_like, is_full_slice from .variable import IndexVariable, Variable diff --git a/xarray/core/combine.py b/xarray/core/combine.py index 6d922064f6f..0b18aa47dee 100644 --- a/xarray/core/combine.py +++ b/xarray/core/combine.py @@ -4,12 +4,12 @@ import pandas as pd -from . import utils, dtypes +from . import dtypes, utils from .alignment import align +from .computation import result_name from .merge import merge from .variable import IndexVariable, Variable, as_variable from .variable import concat as concat_vars -from .computation import result_name def concat(objs, dim=None, data_vars='all', coords='different', diff --git a/xarray/core/common.py b/xarray/core/common.py index 00d0383a727..4e5133fd8c6 100644 --- a/xarray/core/common.py +++ b/xarray/core/common.py @@ -1,8 +1,9 @@ from collections import OrderedDict from contextlib import suppress from textwrap import dedent -from typing import (Any, Callable, Hashable, Iterable, Iterator, List, Mapping, - MutableMapping, Optional, Tuple, TypeVar, Union) +from typing import ( + Any, Callable, Hashable, Iterable, Iterator, List, Mapping, MutableMapping, + Optional, Tuple, TypeVar, Union) import numpy as np import pandas as pd @@ -13,7 +14,6 @@ from .pycompat import dask_array_type from .utils import Frozen, ReprObject, SortedKeysDict, either_dict_or_kwargs - # Used as a sentinel value to indicate a all dimensions ALL_DIMS = ReprObject('') diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index e9ec1445dd4..ced1dba09e2 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -8,7 +8,7 @@ from distutils.version import LooseVersion from numbers import Number from typing import ( - Any, Callable, Dict, List, Optional, Set, Tuple, TypeVar, Union, Sequence) + Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, TypeVar, Union) import numpy as np import pandas as pd @@ -35,8 +35,7 @@ from .pycompat import TYPE_CHECKING, dask_array_type from .utils import ( Frozen, SortedKeysDict, _check_inplace, decode_numpy_dict_values, - either_dict_or_kwargs, ensure_us_time_resolution, hashable, is_dict_like, - maybe_wrap_array) + either_dict_or_kwargs, hashable, maybe_wrap_array) from .variable import IndexVariable, Variable, as_variable, broadcast_variables if TYPE_CHECKING: @@ -4145,7 +4144,7 @@ def _integrate_one(self, coord, datetime_unit=None): from .variable import Variable if coord not in self.variables and coord not in self.dims: - raise ValueError('Coordinate {} does not exist.'.format(dim)) + raise ValueError('Coordinate {} does not exist.'.format(coord)) coord_var = self[coord].variable if coord_var.ndim != 1: diff --git a/xarray/core/duck_array_ops.py b/xarray/core/duck_array_ops.py index b37e01cb7af..bc66eb71ced 100644 --- a/xarray/core/duck_array_ops.py +++ b/xarray/core/duck_array_ops.py @@ -4,9 +4,9 @@ accept or return xarray objects. """ import contextlib -from functools import partial import inspect import warnings +from functools import partial import numpy as np import pandas as pd diff --git a/xarray/core/missing.py b/xarray/core/missing.py index 3931512325e..6009983beb2 100644 --- a/xarray/core/missing.py +++ b/xarray/core/missing.py @@ -9,7 +9,7 @@ from . import utils from .common import _contains_datetime_like_objects from .computation import apply_ufunc -from .duck_array_ops import dask_array_type, datetime_to_numeric +from .duck_array_ops import dask_array_type from .utils import OrderedSet, is_scalar from .variable import Variable, broadcast_variables diff --git a/xarray/core/options.py b/xarray/core/options.py index d441a81d325..532d86a8f38 100644 --- a/xarray/core/options.py +++ b/xarray/core/options.py @@ -59,7 +59,7 @@ def _warn_on_setting_enable_cftimeindex(enable_cftimeindex): def _get_keep_attrs(default): global_choice = OPTIONS['keep_attrs'] - if global_choice is 'default': + if global_choice == 'default': return default elif global_choice in [True, False]: return global_choice diff --git a/xarray/core/resample_cftime.py b/xarray/core/resample_cftime.py index e7f41be8667..cac78aabe98 100644 --- a/xarray/core/resample_cftime.py +++ b/xarray/core/resample_cftime.py @@ -36,14 +36,16 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. -from ..coding.cftimeindex import CFTimeIndex -from ..coding.cftime_offsets import (cftime_range, normalize_date, - Day, MonthEnd, QuarterEnd, YearEnd, - CFTIME_TICKS, to_offset) import datetime + import numpy as np import pandas as pd +from ..coding.cftime_offsets import ( + CFTIME_TICKS, Day, MonthEnd, QuarterEnd, YearEnd, cftime_range, + normalize_date, to_offset) +from ..coding.cftimeindex import CFTimeIndex + class CFTimeGrouper: """This is a simple container for the grouping parameters that implements a diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py index a884963bf06..4773512cdc4 100644 --- a/xarray/core/rolling.py +++ b/xarray/core/rolling.py @@ -7,8 +7,8 @@ from . import dtypes, duck_array_ops, utils from .dask_array_ops import dask_rolling_wrapper from .ops import ( - bn, has_bottleneck, inject_coarsen_methods, - inject_bottleneck_rolling_methods, inject_datasetrolling_methods) + bn, has_bottleneck, inject_bottleneck_rolling_methods, + inject_coarsen_methods, inject_datasetrolling_methods) from .pycompat import dask_array_type diff --git a/xarray/core/utils.py b/xarray/core/utils.py index 386019a3dbf..9b762ab99c7 100644 --- a/xarray/core/utils.py +++ b/xarray/core/utils.py @@ -7,16 +7,16 @@ import re import warnings from collections import OrderedDict -from typing import (AbstractSet, Any, Callable, Container, Dict, Hashable, - Iterable, Iterator, Optional, Sequence, - Tuple, TypeVar, cast) +from typing import ( + AbstractSet, Any, Callable, Container, Dict, Hashable, Iterable, Iterator, + Mapping, MutableMapping, MutableSet, Optional, Sequence, Tuple, TypeVar, + cast) import numpy as np import pandas as pd from .pycompat import dask_array_type -from typing import Mapping, MutableMapping, MutableSet try: # Fix typed collections in Python 3.5.0~3.5.2 from .pycompat import Mapping, MutableMapping, MutableSet # noqa: F811 except ImportError: diff --git a/xarray/plot/__init__.py b/xarray/plot/__init__.py index 51712e78bf8..adda541c21d 100644 --- a/xarray/plot/__init__.py +++ b/xarray/plot/__init__.py @@ -1,7 +1,5 @@ -from .plot import (plot, line, step, contourf, contour, - hist, imshow, pcolormesh) - from .facetgrid import FacetGrid +from .plot import contour, contourf, hist, imshow, line, pcolormesh, plot, step __all__ = [ 'plot', diff --git a/xarray/plot/facetgrid.py b/xarray/plot/facetgrid.py index 4a8d77d7b86..9d2b4848319 100644 --- a/xarray/plot/facetgrid.py +++ b/xarray/plot/facetgrid.py @@ -1,14 +1,13 @@ import functools import itertools import warnings -from inspect import getfullargspec import numpy as np from ..core.formatting import format_item from .utils import ( - _infer_xy_labels, _process_cmap_cbar_kwargs, - import_matplotlib_pyplot, label_from_attrs) + _infer_xy_labels, _process_cmap_cbar_kwargs, import_matplotlib_pyplot, + label_from_attrs) # Overrides axes.labelsize, xtick.major.size, ytick.major.size # from mpl.rcParams @@ -483,7 +482,7 @@ def map(self, func, *args, **kwargs): # TODO: better way to verify that an artist is mappable? # https://stackoverflow.com/questions/33023036/is-it-possible-to-detect-if-a-matplotlib-artist-is-a-mappable-suitable-for-use-w#33023522 if (maybe_mappable and - hasattr(maybe_mappable, 'autoscale_None')): + hasattr(maybe_mappable, 'autoscale_None')): self._mappables.append(maybe_mappable) self._finalize_grid(*args[:2]) diff --git a/xarray/plot/utils.py b/xarray/plot/utils.py index 0a507993cd6..18215479d8c 100644 --- a/xarray/plot/utils.py +++ b/xarray/plot/utils.py @@ -2,15 +2,14 @@ import textwrap import warnings from datetime import datetime +from distutils.version import LooseVersion +from inspect import getfullargspec import numpy as np import pandas as pd -from inspect import getfullargspec - from ..core.options import OPTIONS from ..core.utils import is_scalar -from distutils.version import LooseVersion try: import nc_time_axis diff --git a/xarray/testing.py b/xarray/testing.py index eb8a0e8603d..ed015181dfd 100644 --- a/xarray/testing.py +++ b/xarray/testing.py @@ -4,8 +4,7 @@ import numpy as np import pandas as pd -from xarray.core import duck_array_ops -from xarray.core import formatting +from xarray.core import duck_array_ops, formatting from xarray.core.indexes import default_indexes diff --git a/xarray/tests/__init__.py b/xarray/tests/__init__.py index 5e559fce526..d3fe5e167a6 100644 --- a/xarray/tests/__init__.py +++ b/xarray/tests/__init__.py @@ -1,19 +1,19 @@ +import importlib +import re import warnings from contextlib import contextmanager from distutils import version -import re -import importlib -from unittest import mock +from unittest import mock # noqa import numpy as np -from numpy.testing import assert_array_equal # noqa: F401 -from xarray.core.duck_array_ops import allclose_or_equiv # noqa import pytest +from numpy.testing import assert_array_equal # noqa: F401 +import xarray.testing from xarray.core import utils -from xarray.core.options import set_options +from xarray.core.duck_array_ops import allclose_or_equiv # noqa from xarray.core.indexing import ExplicitlyIndexed -import xarray.testing +from xarray.core.options import set_options from xarray.plot.utils import import_seaborn try: diff --git a/xarray/tests/test_accessor_str.py b/xarray/tests/test_accessor_str.py index 26d5e385df3..800096b806b 100644 --- a/xarray/tests/test_accessor_str.py +++ b/xarray/tests/test_accessor_str.py @@ -39,12 +39,12 @@ import re -import pytest import numpy as np +import pytest + import xarray as xr -from . import ( - assert_array_equal, assert_equal, has_dask, raises_regex, requires_dask) +from . import assert_equal, requires_dask @pytest.fixture(params=[np.str_, np.bytes_]) @@ -138,14 +138,14 @@ def test_replace(dtype): def test_replace_callable(): values = xr.DataArray(['fooBAD__barBAD']) # test with callable - repl = lambda m: m.group(0).swapcase() + repl = lambda m: m.group(0).swapcase() # noqa result = values.str.replace('[a-z][A-Z]{2}', repl, n=2) exp = xr.DataArray(['foObaD__baRbaD']) assert_equal(result, exp) # test regex named groups values = xr.DataArray(['Foo Bar Baz']) pat = r"(?P\w+) (?P\w+) (?P\w+)" - repl = lambda m: m.group('middle').swapcase() + repl = lambda m: m.group('middle').swapcase() # noqa result = values.str.replace(pat, repl) exp = xr.DataArray(['bAR']) assert_equal(result, exp) diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index ad66ecf1286..e71181f52c9 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -2,15 +2,15 @@ import itertools import math import os.path -from pathlib import Path import pickle import shutil import sys import tempfile -from typing import Optional import warnings from contextlib import ExitStack from io import BytesIO +from pathlib import Path +from typing import Optional import numpy as np import pandas as pd @@ -18,26 +18,26 @@ import xarray as xr from xarray import ( - DataArray, Dataset, backends, open_dataarray, open_dataset, open_mfdataset, - save_mfdataset, load_dataset, load_dataarray) + DataArray, Dataset, backends, load_dataarray, load_dataset, open_dataarray, + open_dataset, open_mfdataset, save_mfdataset) from xarray.backends.common import robust_getitem from xarray.backends.netCDF4_ import _extract_nc4_variable_encoding from xarray.backends.pydap_ import PydapDataStore +from xarray.coding.variables import SerializationWarning from xarray.core import indexing from xarray.core.options import set_options from xarray.core.pycompat import dask_array_type from xarray.tests import mock -from xarray.coding.variables import SerializationWarning from . import ( assert_allclose, assert_array_equal, assert_equal, assert_identical, has_dask, has_netCDF4, has_scipy, network, raises_regex, requires_cfgrib, - requires_cftime, requires_dask, requires_h5netcdf, requires_netCDF4, - requires_pathlib, requires_pseudonetcdf, requires_pydap, requires_pynio, - requires_rasterio, requires_scipy, requires_scipy_or_netCDF4, - requires_zarr, requires_h5fileobj) -from .test_coding_times import (_STANDARD_CALENDARS, _NON_STANDARD_CALENDARS, - _ALL_CALENDARS) + requires_cftime, requires_dask, requires_h5fileobj, requires_h5netcdf, + requires_netCDF4, requires_pathlib, requires_pseudonetcdf, requires_pydap, + requires_pynio, requires_rasterio, requires_scipy, + requires_scipy_or_netCDF4, requires_zarr) +from .test_coding_times import ( + _ALL_CALENDARS, _NON_STANDARD_CALENDARS, _STANDARD_CALENDARS) from .test_dataset import create_test_data try: diff --git a/xarray/tests/test_backends_lru_cache.py b/xarray/tests/test_backends_lru_cache.py index d64d718f2f7..aa97f5fb4cb 100644 --- a/xarray/tests/test_backends_lru_cache.py +++ b/xarray/tests/test_backends_lru_cache.py @@ -1,4 +1,5 @@ from unittest import mock + import pytest from xarray.backends.lru_cache import LRUCache diff --git a/xarray/tests/test_cftime_offsets.py b/xarray/tests/test_cftime_offsets.py index 1cf257c96eb..b3560fe3039 100644 --- a/xarray/tests/test_cftime_offsets.py +++ b/xarray/tests/test_cftime_offsets.py @@ -6,8 +6,8 @@ from xarray import CFTimeIndex from xarray.coding.cftime_offsets import ( - _MONTH_ABBREVIATIONS, BaseCFTimeOffset, Day, Hour, Minute, Second, - MonthBegin, MonthEnd, YearBegin, YearEnd, QuarterBegin, QuarterEnd, + _MONTH_ABBREVIATIONS, BaseCFTimeOffset, Day, Hour, Minute, MonthBegin, + MonthEnd, QuarterBegin, QuarterEnd, Second, YearBegin, YearEnd, _days_in_month, cftime_range, get_date_type, to_cftime_datetime, to_offset) cftime = pytest.importorskip('cftime') diff --git a/xarray/tests/test_cftimeindex.py b/xarray/tests/test_cftimeindex.py index 999af4c9f86..56c01fbdc28 100644 --- a/xarray/tests/test_cftimeindex.py +++ b/xarray/tests/test_cftimeindex.py @@ -8,7 +8,7 @@ from xarray.coding.cftimeindex import ( CFTimeIndex, _parse_array_of_cftime_strings, _parse_iso8601_with_reso, _parsed_string_to_bounds, assert_all_valid_date_type, parse_iso8601) -from xarray.tests import assert_array_equal, assert_allclose, assert_identical +from xarray.tests import assert_array_equal, assert_identical from . import ( has_cftime, has_cftime_1_0_2_1, has_cftime_or_netCDF4, raises_regex, diff --git a/xarray/tests/test_cftimeindex_resample.py b/xarray/tests/test_cftimeindex_resample.py index 7aca4492680..108b303e0c0 100644 --- a/xarray/tests/test_cftimeindex_resample.py +++ b/xarray/tests/test_cftimeindex_resample.py @@ -1,12 +1,12 @@ -import pytest - import datetime + import numpy as np import pandas as pd +import pytest + import xarray as xr from xarray.core.resample_cftime import CFTimeGrouper - pytest.importorskip('cftime') pytest.importorskip('pandas', minversion='0.24') diff --git a/xarray/tests/test_coding_times.py b/xarray/tests/test_coding_times.py index d40abd4acc3..421637dd7e3 100644 --- a/xarray/tests/test_coding_times.py +++ b/xarray/tests/test_coding_times.py @@ -15,7 +15,7 @@ from . import ( assert_array_equal, has_cftime, has_cftime_or_netCDF4, has_dask, - requires_cftime_or_netCDF4, requires_cftime) + requires_cftime, requires_cftime_or_netCDF4) try: from pandas.errors import OutOfBoundsDatetime diff --git a/xarray/tests/test_combine.py b/xarray/tests/test_combine.py index a477df0b0d4..e9b63dd18fc 100644 --- a/xarray/tests/test_combine.py +++ b/xarray/tests/test_combine.py @@ -14,8 +14,8 @@ _infer_tile_ids_from_nested_list, _new_tile_id) from . import ( - InaccessibleArray, assert_array_equal, - assert_equal, assert_identical, raises_regex, requires_dask) + InaccessibleArray, assert_array_equal, assert_equal, assert_identical, + raises_regex, requires_dask) from .test_dataset import create_test_data diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index ab1f56abd4c..fd9076e7f65 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -1,9 +1,9 @@ import pickle +import sys import warnings from collections import OrderedDict from copy import deepcopy from textwrap import dedent -import sys import numpy as np import pandas as pd @@ -12,7 +12,7 @@ import xarray as xr from xarray import ( DataArray, Dataset, IndexVariable, Variable, align, broadcast) -from xarray.coding.times import CFDatetimeCoder, _import_cftime +from xarray.coding.times import CFDatetimeCoder from xarray.convert import from_cdms2 from xarray.core import dtypes from xarray.core.common import ALL_DIMS, full_like @@ -1259,18 +1259,6 @@ def test_reindex_like_no_index(self): ValueError, 'different size for unlabeled'): foo.reindex_like(bar) - @pytest.mark.parametrize('fill_value', [dtypes.NA, 2, 2.0]) - def test_reindex_fill_value(self, fill_value): - foo = DataArray([10, 20], dims='y', coords={'y': [0, 1]}) - bar = DataArray([10, 20, 30], dims='y', coords={'y': [0, 1, 2]}) - if fill_value == dtypes.NA: - # if we supply the default, we expect the missing value for a - # float array - fill_value = np.nan - actual = x.reindex_like(bar, fill_value=fill_value) - expected = DataArray([10, 20, fill_value], coords=[('y', [0, 1, 2])]) - assert_identical(expected, actual) - @pytest.mark.filterwarnings('ignore:Indexer has dimensions') def test_reindex_regressions(self): # regression test for #279 @@ -1644,8 +1632,8 @@ def test_math_name(self): assert (a + a.rename(None)).name is None assert (a + a.rename('bar')).name is None assert (a + a).name == 'foo' - assert (+a['x']).name is 'x' - assert (a['x'] + 0).name is 'x' + assert (+a['x']).name == 'x' + assert (a['x'] + 0).name == 'x' assert (a + a['x']).name is None def test_math_with_coords(self): diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index dd7d2a98333..98e488552d1 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -22,8 +22,8 @@ from . import ( InaccessibleArray, UnexpectedDataAccess, assert_allclose, assert_array_equal, assert_equal, assert_identical, has_cftime, has_dask, - raises_regex, requires_bottleneck, requires_dask, requires_scipy, - source_ndarray, requires_cftime) + raises_regex, requires_bottleneck, requires_cftime, requires_dask, + requires_scipy, source_ndarray) try: import dask.array as da @@ -4756,9 +4756,9 @@ def test_rolling_wrapped_bottleneck(ds, name, center, min_periods, key): func_name = 'move_{0}'.format(name) actual = getattr(rolling_obj, name)() - if key is 'z1': # z1 does not depend on 'Time' axis. Stored as it is. + if key == 'z1': # z1 does not depend on 'Time' axis. Stored as it is. expected = ds[key] - elif key is 'z2': + elif key == 'z2': expected = getattr(bn, func_name)(ds[key].values, window=7, axis=0, min_count=min_periods) assert_array_equal(actual[key].values, expected) diff --git a/xarray/tests/test_distributed.py b/xarray/tests/test_distributed.py index 17f655cef8d..98c53ef2b12 100644 --- a/xarray/tests/test_distributed.py +++ b/xarray/tests/test_distributed.py @@ -1,4 +1,5 @@ """ isort:skip_file """ +# flake8: noqa: E402 - ignore linters re order of imports import pickle import pytest @@ -28,6 +29,7 @@ da = pytest.importorskip('dask.array') +loop = loop # loop is an imported fixture, which flake8 has issues ack-ing @pytest.fixture diff --git a/xarray/tests/test_duck_array_ops.py b/xarray/tests/test_duck_array_ops.py index 75ab5f52a1b..87a7a2863d3 100644 --- a/xarray/tests/test_duck_array_ops.py +++ b/xarray/tests/test_duck_array_ops.py @@ -7,13 +7,13 @@ import pytest from numpy import array, nan -from xarray import DataArray, Dataset, concat, cftime_range +from xarray import DataArray, Dataset, cftime_range, concat from xarray.core import dtypes, duck_array_ops from xarray.core.duck_array_ops import ( array_notnull_equiv, concatenate, count, first, gradient, last, mean, rolling_window, stack, where) from xarray.core.pycompat import dask_array_type -from xarray.testing import assert_allclose, assert_equal, assert_identical +from xarray.testing import assert_allclose, assert_equal from . import ( assert_array_equal, has_dask, has_np113, raises_regex, requires_cftime, diff --git a/xarray/tests/test_interp.py b/xarray/tests/test_interp.py index a11e4b9e79a..252f8bcacd4 100644 --- a/xarray/tests/test_interp.py +++ b/xarray/tests/test_interp.py @@ -6,8 +6,8 @@ from xarray.tests import ( assert_allclose, assert_equal, requires_cftime, requires_scipy) -from . import has_dask, has_scipy from ..coding.cftimeindex import _parse_array_of_cftime_strings +from . import has_dask, has_scipy from .test_dataset import create_test_data try: diff --git a/xarray/tests/test_merge.py b/xarray/tests/test_merge.py index 0d76db1d1ee..c45195eaa7f 100644 --- a/xarray/tests/test_merge.py +++ b/xarray/tests/test_merge.py @@ -2,7 +2,7 @@ import pytest import xarray as xr -from xarray.core import merge, dtypes +from xarray.core import dtypes, merge from . import raises_regex from .test_dataset import create_test_data diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index a79becb3bda..a0952cac47e 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -14,10 +14,9 @@ import_seaborn, label_from_attrs) from . import ( - assert_array_equal, assert_equal, raises_regex, requires_cftime, - requires_matplotlib, requires_matplotlib2, requires_seaborn, - requires_nc_time_axis) -from . import has_nc_time_axis + assert_array_equal, assert_equal, has_nc_time_axis, raises_regex, + requires_cftime, requires_matplotlib, requires_matplotlib2, + requires_nc_time_axis, requires_seaborn) # import mpl and change the backend before other mpl imports try: diff --git a/xarray/tutorial.py b/xarray/tutorial.py index 1a977450ed6..01d4f181d7f 100644 --- a/xarray/tutorial.py +++ b/xarray/tutorial.py @@ -7,7 +7,6 @@ ''' import hashlib import os as _os -import warnings from urllib.request import urlretrieve from .backends.api import open_dataset as _open_dataset