From 24d49fcd723f20b09998c302dc6003b8de69e595 Mon Sep 17 00:00:00 2001 From: crusaderky Date: Thu, 9 May 2019 17:01:36 +0100 Subject: [PATCH] Base classes in Python 3 don't need to subclass object (#2950) * Base classes in Python 3 don't need to subclass object * What's new --- asv_bench/benchmarks/dataset_io.py | 8 ++++---- asv_bench/benchmarks/indexing.py | 2 +- asv_bench/benchmarks/interp.py | 2 +- asv_bench/benchmarks/reindexing.py | 2 +- asv_bench/benchmarks/rolling.py | 2 +- asv_bench/benchmarks/unstacking.py | 2 +- doc/contributing.rst | 2 +- doc/examples/_code/accessor_example.py | 2 +- doc/whats-new.rst | 4 +++- xarray/backends/api.py | 2 +- xarray/backends/common.py | 2 +- xarray/backends/file_manager.py | 4 ++-- xarray/backends/locks.py | 4 ++-- xarray/backends/netCDF4_.py | 2 +- xarray/coding/cftime_offsets.py | 2 +- xarray/coding/variables.py | 2 +- xarray/core/accessors.py | 2 +- xarray/core/arithmetic.py | 2 +- xarray/core/computation.py | 2 +- xarray/core/coordinates.py | 2 +- xarray/core/dataarray.py | 2 +- xarray/core/dataset.py | 2 +- xarray/core/dtypes.py | 4 ++-- xarray/core/extensions.py | 4 ++-- xarray/core/groupby.py | 2 +- xarray/core/indexing.py | 6 +++--- xarray/core/missing.py | 2 +- xarray/core/nputils.py | 2 +- xarray/core/options.py | 2 +- xarray/core/resample.py | 2 +- xarray/core/resample_cftime.py | 2 +- xarray/core/rolling.py | 4 ++-- xarray/plot/facetgrid.py | 2 +- xarray/plot/plot.py | 2 +- xarray/tests/__init__.py | 4 ++-- xarray/tests/test_accessors.py | 2 +- xarray/tests/test_backends.py | 24 ++++++++++++------------ xarray/tests/test_combine.py | 16 ++++++++-------- xarray/tests/test_computation.py | 2 +- xarray/tests/test_conventions.py | 8 ++++---- xarray/tests/test_dask.py | 4 ++-- xarray/tests/test_dataarray.py | 4 ++-- xarray/tests/test_dataset.py | 4 ++-- xarray/tests/test_duck_array_ops.py | 2 +- xarray/tests/test_extensions.py | 10 +++++----- xarray/tests/test_formatting.py | 2 +- xarray/tests/test_indexing.py | 10 +++++----- xarray/tests/test_merge.py | 8 ++++---- xarray/tests/test_options.py | 2 +- xarray/tests/test_plot.py | 10 +++++----- xarray/tests/test_tutorial.py | 2 +- xarray/tests/test_ufuncs.py | 2 +- xarray/tests/test_utils.py | 10 +++++----- xarray/tests/test_variable.py | 8 ++++---- xarray/ufuncs.py | 2 +- 55 files changed, 114 insertions(+), 112 deletions(-) diff --git a/asv_bench/benchmarks/dataset_io.py b/asv_bench/benchmarks/dataset_io.py index 3e070e1355b..07bcc6d71b4 100644 --- a/asv_bench/benchmarks/dataset_io.py +++ b/asv_bench/benchmarks/dataset_io.py @@ -19,7 +19,7 @@ os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE' -class IOSingleNetCDF(object): +class IOSingleNetCDF: """ A few examples that benchmark reading/writing a single netCDF file with xarray @@ -214,7 +214,7 @@ def time_load_dataset_scipy_with_time_chunks(self): chunks=self.time_chunks).load() -class IOMultipleNetCDF(object): +class IOMultipleNetCDF: """ A few examples that benchmark reading/writing multiple netCDF files with xarray @@ -419,7 +419,7 @@ def create_delayed_write(): return ds.to_netcdf('file.nc', engine='netcdf4', compute=False) -class IOWriteNetCDFDask(object): +class IOWriteNetCDFDask: timeout = 60 repeat = 1 number = 5 @@ -432,7 +432,7 @@ def time_write(self): self.write.compute() -class IOWriteNetCDFDaskDistributed(object): +class IOWriteNetCDFDaskDistributed: def setup(self): try: import distributed diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 54262b12a19..84e7fea33af 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -58,7 +58,7 @@ } -class Base(object): +class Base: def setup(self, key): self.ds = xr.Dataset( {'var1': (('x', 'y'), randn((nx, ny), frac_nan=0.1)), diff --git a/asv_bench/benchmarks/interp.py b/asv_bench/benchmarks/interp.py index edec6df34dd..c3c1b7c533b 100644 --- a/asv_bench/benchmarks/interp.py +++ b/asv_bench/benchmarks/interp.py @@ -24,7 +24,7 @@ new_y_long = np.linspace(0.1, 0.9, 1000) -class Interpolation(object): +class Interpolation: def setup(self, *args, **kwargs): self.ds = xr.Dataset( {'var1': (('x', 'y'), randn_xy), diff --git a/asv_bench/benchmarks/reindexing.py b/asv_bench/benchmarks/reindexing.py index 28e14d52e89..42529f2cfe6 100644 --- a/asv_bench/benchmarks/reindexing.py +++ b/asv_bench/benchmarks/reindexing.py @@ -7,7 +7,7 @@ from . import requires_dask -class Reindex(object): +class Reindex: def setup(self): data = np.random.RandomState(0).randn(1000, 100, 100) self.ds = xr.Dataset({'temperature': (('time', 'x', 'y'), data)}, diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index 5ba7406f6e0..7eb9f8a2358 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -19,7 +19,7 @@ randn_long = randn((long_nx, ), frac_nan=0.1) -class Rolling(object): +class Rolling: def setup(self, *args, **kwargs): self.ds = xr.Dataset( {'var1': (('x', 'y'), randn_xy), diff --git a/asv_bench/benchmarks/unstacking.py b/asv_bench/benchmarks/unstacking.py index 54436b422e9..d050e864e86 100644 --- a/asv_bench/benchmarks/unstacking.py +++ b/asv_bench/benchmarks/unstacking.py @@ -7,7 +7,7 @@ from . import requires_dask -class Unstacking(object): +class Unstacking: def setup(self): data = np.random.RandomState(0).randn(1, 1000, 500) self.ds = xr.DataArray(data).stack(flat_dim=['dim_1', 'dim_2']) diff --git a/doc/contributing.rst b/doc/contributing.rst index d216488e805..fba09497abe 100644 --- a/doc/contributing.rst +++ b/doc/contributing.rst @@ -457,7 +457,7 @@ typically find tests wrapped in a class. .. code-block:: python - class TestReallyCoolFeature(object): + class TestReallyCoolFeature: .... Going forward, we are moving to a more *functional* style using the diff --git a/doc/examples/_code/accessor_example.py b/doc/examples/_code/accessor_example.py index a11ebf9329b..d179d38fba9 100644 --- a/doc/examples/_code/accessor_example.py +++ b/doc/examples/_code/accessor_example.py @@ -2,7 +2,7 @@ @xr.register_dataset_accessor('geo') -class GeoAccessor(object): +class GeoAccessor: def __init__(self, xarray_obj): self._obj = xarray_obj self._center = None diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 68f0fb142dc..ac641d0df37 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -27,7 +27,9 @@ Enhancements - Character arrays' character dimension name decoding and encoding handled by ``var.encoding['char_dim_name']`` (:issue:`2895`) By `James McCreight `_. - +- Clean up Python 2 compatibility in code (:issue:`2950`) + By `Guido Imperiale `_. + Bug fixes ~~~~~~~~~ diff --git a/xarray/backends/api.py b/xarray/backends/api.py index afb69f6e9e9..7c5040580fe 100644 --- a/xarray/backends/api.py +++ b/xarray/backends/api.py @@ -529,7 +529,7 @@ def open_dataarray(filename_or_obj, group=None, decode_cf=True, return data_array -class _MultiFileCloser(object): +class _MultiFileCloser: def __init__(self, file_objs): self.file_objs = file_objs diff --git a/xarray/backends/common.py b/xarray/backends/common.py index a52daaaa65c..5819292bb8a 100644 --- a/xarray/backends/common.py +++ b/xarray/backends/common.py @@ -154,7 +154,7 @@ def __exit__(self, exception_type, exception_value, traceback): self.close() -class ArrayWriter(object): +class ArrayWriter: def __init__(self, lock=None): self.sources = [] self.targets = [] diff --git a/xarray/backends/file_manager.py b/xarray/backends/file_manager.py index d0efba86bf9..5955ef54d6e 100644 --- a/xarray/backends/file_manager.py +++ b/xarray/backends/file_manager.py @@ -19,7 +19,7 @@ _DEFAULT_MODE = utils.ReprObject('') -class FileManager(object): +class FileManager: """Manager for acquiring and closing a file object. Use FileManager subclasses (CachingFileManager in particular) on backend @@ -237,7 +237,7 @@ def __repr__(self): type(self).__name__, self._opener, args_string, self._kwargs) -class _RefCounter(object): +class _RefCounter: """Class for keeping track of reference counts.""" def __init__(self, counts): self._counts = counts diff --git a/xarray/backends/locks.py b/xarray/backends/locks.py index bca27a0bbc1..65150562538 100644 --- a/xarray/backends/locks.py +++ b/xarray/backends/locks.py @@ -135,7 +135,7 @@ def acquire(lock, blocking=True): return lock.acquire(blocking) -class CombinedLock(object): +class CombinedLock: """A combination of multiple locks. Like a locked door, a CombinedLock is locked if any of its constituent @@ -167,7 +167,7 @@ def __repr__(self): return "CombinedLock(%r)" % list(self.locks) -class DummyLock(object): +class DummyLock: """DummyLock provides the lock API without any actual locking.""" def acquire(self, blocking=True): diff --git a/xarray/backends/netCDF4_.py b/xarray/backends/netCDF4_.py index b26d5575d23..b3bab9617ee 100644 --- a/xarray/backends/netCDF4_.py +++ b/xarray/backends/netCDF4_.py @@ -228,7 +228,7 @@ def _extract_nc4_variable_encoding(variable, raise_on_invalid=False, return encoding -class GroupWrapper(object): +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/cftime_offsets.py b/xarray/coding/cftime_offsets.py index 2ee38a20a4d..e89118e8be4 100644 --- a/xarray/coding/cftime_offsets.py +++ b/xarray/coding/cftime_offsets.py @@ -77,7 +77,7 @@ def get_date_type(calendar): return calendars[calendar] -class BaseCFTimeOffset(object): +class BaseCFTimeOffset: _freq = None # type: ClassVar[str] _day_option = None # type: ClassVar[str] diff --git a/xarray/coding/variables.py b/xarray/coding/variables.py index 1f74181f3b3..ae8b97c7352 100644 --- a/xarray/coding/variables.py +++ b/xarray/coding/variables.py @@ -15,7 +15,7 @@ class SerializationWarning(RuntimeWarning): """Warnings about encoding/decoding issues in serialization.""" -class VariableCoder(object): +class VariableCoder: """Base class for encoding and decoding transformations on variables. We use coders for transforming variables between xarray's data model and diff --git a/xarray/core/accessors.py b/xarray/core/accessors.py index 10c900c4ad1..640060fafe5 100644 --- a/xarray/core/accessors.py +++ b/xarray/core/accessors.py @@ -110,7 +110,7 @@ def _round_field(values, name, freq): return _round_series(values, name, freq) -class DatetimeAccessor(object): +class DatetimeAccessor: """Access datetime fields for DataArrays with datetime-like dtypes. Similar to pandas, fields can be accessed through the `.dt` attribute diff --git a/xarray/core/arithmetic.py b/xarray/core/arithmetic.py index 39901f0befd..9da4c84697e 100644 --- a/xarray/core/arithmetic.py +++ b/xarray/core/arithmetic.py @@ -8,7 +8,7 @@ from .utils import not_implemented -class SupportsArithmetic(object): +class SupportsArithmetic: """Base class for xarray types that support arithmetic. Used by Dataset, DataArray, Variable and GroupBy. diff --git a/xarray/core/computation.py b/xarray/core/computation.py index 451d95ee542..6a6fa74c858 100644 --- a/xarray/core/computation.py +++ b/xarray/core/computation.py @@ -29,7 +29,7 @@ _JOINS_WITHOUT_FILL_VALUES = frozenset({'inner', 'exact'}) -class _UFuncSignature(object): +class _UFuncSignature: """Core dimensions signature for a given function. Based on the signature provided by generalized ufuncs in NumPy. diff --git a/xarray/core/coordinates.py b/xarray/core/coordinates.py index 9347ba6b6db..ea3eaa0f4f2 100644 --- a/xarray/core/coordinates.py +++ b/xarray/core/coordinates.py @@ -258,7 +258,7 @@ def _ipython_key_completions_(self): return self._data._ipython_key_completions_() -class LevelCoordinatesSource(object): +class LevelCoordinatesSource: """Iterator for MultiIndex level coordinates. Used for attribute style lookup with AttrAccessMixin. Not returned directly diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index 15e2e00dc21..8d3836f5d8c 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -92,7 +92,7 @@ def _infer_coords_and_dims(shape, coords, dims): return new_coords, dims -class _LocIndexer(object): +class _LocIndexer: def __init__(self, data_array): self.data_array = data_array diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 79a42b303c2..753b70d2ab7 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -303,7 +303,7 @@ def _ipython_key_completions_(self): if key not in self._dataset._coord_names] -class _LocIndexer(object): +class _LocIndexer: def __init__(self, dataset): self.dataset = dataset diff --git a/xarray/core/dtypes.py b/xarray/core/dtypes.py index 00ff7958183..794f2b62183 100644 --- a/xarray/core/dtypes.py +++ b/xarray/core/dtypes.py @@ -9,7 +9,7 @@ @functools.total_ordering -class AlwaysGreaterThan(object): +class AlwaysGreaterThan: def __gt__(self, other): return True @@ -18,7 +18,7 @@ def __eq__(self, other): @functools.total_ordering -class AlwaysLessThan(object): +class AlwaysLessThan: def __lt__(self, other): return True diff --git a/xarray/core/extensions.py b/xarray/core/extensions.py index 574c05f1a6b..cb34e87f88d 100644 --- a/xarray/core/extensions.py +++ b/xarray/core/extensions.py @@ -8,7 +8,7 @@ class AccessorRegistrationWarning(Warning): """Warning for conflicts in accessor registration.""" -class _CachedAccessor(object): +class _CachedAccessor: """Custom property-like object (descriptor) for caching accessors.""" def __init__(self, name, accessor): @@ -81,7 +81,7 @@ def register_dataset_accessor(name): import xarray as xr @xr.register_dataset_accessor('geo') - class GeoAccessor(object): + class GeoAccessor: def __init__(self, xarray_obj): self._obj = xarray_obj diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index 4c98ea90389..82a92044caf 100644 --- a/xarray/core/groupby.py +++ b/xarray/core/groupby.py @@ -113,7 +113,7 @@ def _inverse_permutation_indices(positions): return indices -class _DummyGroup(object): +class _DummyGroup: """Class for keeping track of grouped dimensions without coordinates. Should not be user visible. diff --git a/xarray/core/indexing.py b/xarray/core/indexing.py index 65a123c3319..1effb9347dd 100644 --- a/xarray/core/indexing.py +++ b/xarray/core/indexing.py @@ -294,7 +294,7 @@ def _index_indexer_1d(old_indexer, applied_indexer, size): return indexer -class ExplicitIndexer(object): +class ExplicitIndexer: """Base class for explicit indexer objects. ExplicitIndexer objects wrap a tuple of values given by their ``tuple`` @@ -430,7 +430,7 @@ def __init__(self, key): super(VectorizedIndexer, self).__init__(new_key) -class ExplicitlyIndexed(object): +class ExplicitlyIndexed: """Mixin to mark support for Indexer subclasses in indexing.""" @@ -740,7 +740,7 @@ def _combine_indexers(old_key, shape, new_key): np.broadcast_arrays(*old_key.tuple))) -class IndexingSupport(object): # could inherit from enum.Enum on Python 3 +class IndexingSupport: # could inherit from enum.Enum on Python 3 # for backends that support only basic indexer BASIC = 'BASIC' # for backends that support basic / outer indexer diff --git a/xarray/core/missing.py b/xarray/core/missing.py index 50c420206cd..3931512325e 100644 --- a/xarray/core/missing.py +++ b/xarray/core/missing.py @@ -14,7 +14,7 @@ from .variable import Variable, broadcast_variables -class BaseInterpolator(object): +class BaseInterpolator: '''gerneric interpolator class for normalizing interpolation methods''' cons_kwargs = {} # type: Dict[str, Any] call_kwargs = {} # type: Dict[str, Any] diff --git a/xarray/core/nputils.py b/xarray/core/nputils.py index 14fbec72341..e96e7911d6d 100644 --- a/xarray/core/nputils.py +++ b/xarray/core/nputils.py @@ -120,7 +120,7 @@ def _advanced_indexer_subspaces(key): return mixed_positions, vindex_positions -class NumpyVIndexAdapter(object): +class NumpyVIndexAdapter: """Object that implements indexing like vindex on a np.ndarray. This is a pure Python implementation of (some of) the logic in this NumPy diff --git a/xarray/core/options.py b/xarray/core/options.py index c9d26c3e577..d441a81d325 100644 --- a/xarray/core/options.py +++ b/xarray/core/options.py @@ -69,7 +69,7 @@ def _get_keep_attrs(default): " True, False or 'default'.") -class set_options(object): +class set_options: """Set options for xarray in a controlled context. Currently supported options: diff --git a/xarray/core/resample.py b/xarray/core/resample.py index 40298f14d08..9e9e3b79e13 100644 --- a/xarray/core/resample.py +++ b/xarray/core/resample.py @@ -4,7 +4,7 @@ RESAMPLE_DIM = '__resample_dim__' -class Resample(object): +class Resample: """An object that extends the `GroupBy` object with additional logic for handling specialized re-sampling operations. diff --git a/xarray/core/resample_cftime.py b/xarray/core/resample_cftime.py index 161945f118d..e7f41be8667 100644 --- a/xarray/core/resample_cftime.py +++ b/xarray/core/resample_cftime.py @@ -45,7 +45,7 @@ import pandas as pd -class CFTimeGrouper(object): +class CFTimeGrouper: """This is a simple container for the grouping parameters that implements a single method, the only one required for resampling in xarray. It cannot be used in a call to groupby like a pandas.Grouper object can.""" diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py index 8a974e2da72..ad9b17fef92 100644 --- a/xarray/core/rolling.py +++ b/xarray/core/rolling.py @@ -12,7 +12,7 @@ from .pycompat import dask_array_type -class Rolling(object): +class Rolling: """A object that implements the moving window pattern. See Also @@ -435,7 +435,7 @@ def construct(self, window_dim, stride=1, fill_value=dtypes.NA): **{self.dim: slice(None, None, stride)}) -class Coarsen(object): +class Coarsen: """A object that implements the coarsen. See Also diff --git a/xarray/plot/facetgrid.py b/xarray/plot/facetgrid.py index 4f0232236f8..4a8d77d7b86 100644 --- a/xarray/plot/facetgrid.py +++ b/xarray/plot/facetgrid.py @@ -30,7 +30,7 @@ def _nicetitle(coord, value, maxchar, template): return title -class FacetGrid(object): +class FacetGrid: """ Initialize the matplotlib figure and FacetGrid object. diff --git a/xarray/plot/plot.py b/xarray/plot/plot.py index 8e2457603d6..316d4fb4dd9 100644 --- a/xarray/plot/plot.py +++ b/xarray/plot/plot.py @@ -410,7 +410,7 @@ def hist(darray, figsize=None, size=None, aspect=None, ax=None, **kwargs): # MUST run before any 2d plotting functions are defined since # _plot2d decorator adds them as methods here. -class _PlotMethods(object): +class _PlotMethods: """ Enables use of xarray.plot functions as attributes on a DataArray. For example, DataArray.plot.imshow diff --git a/xarray/tests/__init__.py b/xarray/tests/__init__.py index 525360701fe..e9d670e4dd9 100644 --- a/xarray/tests/__init__.py +++ b/xarray/tests/__init__.py @@ -151,13 +151,13 @@ def __getitem__(self, key): raise UnexpectedDataAccess("Tried accessing data") -class ReturnItem(object): +class ReturnItem: def __getitem__(self, key): return key -class IndexerMaker(object): +class IndexerMaker: def __init__(self, indexer_cls): self._indexer_cls = indexer_cls diff --git a/xarray/tests/test_accessors.py b/xarray/tests/test_accessors.py index ae95bae3a93..6bda5772143 100644 --- a/xarray/tests/test_accessors.py +++ b/xarray/tests/test_accessors.py @@ -9,7 +9,7 @@ has_dask, raises_regex, requires_dask) -class TestDatetimeAccessor(object): +class TestDatetimeAccessor: @pytest.fixture(autouse=True) def setup(self): nt = 100 diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index 5e28ff46665..a4c0374e158 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -141,13 +141,13 @@ def create_boolean_data(): return Dataset({'x': ('t', [True, False, False, True], attributes)}) -class TestCommon(object): +class TestCommon: def test_robust_getitem(self): class UnreliableArrayFailure(Exception): pass - class UnreliableArray(object): + class UnreliableArray: def __init__(self, array, failures=1): self.array = array self.failures = failures @@ -168,11 +168,11 @@ def __getitem__(self, key): assert actual == 0 -class NetCDF3Only(object): +class NetCDF3Only: pass -class DatasetIOBase(object): +class DatasetIOBase: engine = None # type: Optional[str] file_format = None # type: Optional[str] @@ -2196,7 +2196,7 @@ def test_open_mfdataset_manyfiles(readengine, nfiles, parallel, chunks, @requires_scipy_or_netCDF4 -class TestOpenMFDatasetWithDataVarsAndCoordsKw(object): +class TestOpenMFDatasetWithDataVarsAndCoordsKw: coord_name = 'lon' var_name = 'v1' @@ -2644,7 +2644,7 @@ def test_save_mfdataset_compute_false_roundtrip(self): @requires_scipy_or_netCDF4 @requires_pydap -class TestPydap(object): +class TestPydap: def convert_to_pydap_dataset(self, original): from pydap.model import GridType, BaseType, DatasetType ds = DatasetType('bears', **original.attrs) @@ -2777,7 +2777,7 @@ def test_weakrefs(self): @requires_cfgrib -class TestCfGrib(object): +class TestCfGrib: def test_read(self): expected = {'number': 2, 'time': 3, 'isobaricInhPa': 2, 'latitude': 3, @@ -2800,7 +2800,7 @@ def test_read_filter_by_keys(self): @requires_pseudonetcdf @pytest.mark.filterwarnings('ignore:IOAPI_ISPH is assumed to be 6370000') -class TestPseudoNetCDFFormat(object): +class TestPseudoNetCDFFormat: def open(self, path, **kwargs): return open_dataset(path, engine='pseudonetcdf', **kwargs) @@ -3063,7 +3063,7 @@ def create_tmp_geotiff(nx=4, ny=3, nz=3, @requires_rasterio -class TestRasterio(object): +class TestRasterio: @requires_scipy_or_netCDF4 def test_serialization(self): @@ -3492,7 +3492,7 @@ def test_rasterio_vrt_network(self): assert_equal(expected_val, actual_val) -class TestEncodingInvalid(object): +class TestEncodingInvalid: def test_extract_nc4_variable_encoding(self): var = xr.Variable(('x',), [1, 2, 3], {}, {'foo': 'bar'}) @@ -3521,7 +3521,7 @@ class MiscObject: @requires_netCDF4 -class TestValidateAttrs(object): +class TestValidateAttrs: def test_validating_attrs(self): def new_dataset(): return Dataset({'data': ('y', np.arange(10.0))}, @@ -3611,7 +3611,7 @@ def new_dataset_and_coord_attrs(): @requires_scipy_or_netCDF4 -class TestDataArrayToNetCDF(object): +class TestDataArrayToNetCDF: def test_dataarray_to_netcdf_no_name(self): original_da = DataArray(np.arange(12).reshape((3, 4))) diff --git a/xarray/tests/test_combine.py b/xarray/tests/test_combine.py index 6d0f4626086..1d8ed169d29 100644 --- a/xarray/tests/test_combine.py +++ b/xarray/tests/test_combine.py @@ -18,7 +18,7 @@ from .test_dataset import create_test_data -class TestConcatDataset(object): +class TestConcatDataset: def test_concat(self): # TODO: simplify and split this test case @@ -238,7 +238,7 @@ def test_concat_multiindex(self): assert isinstance(actual.x.to_index(), pd.MultiIndex) -class TestConcatDataArray(object): +class TestConcatDataArray: def test_concat(self): ds = Dataset({'foo': (['x', 'y'], np.random.random((2, 3))), 'bar': (['x', 'y'], np.random.random((2, 3)))}, @@ -307,7 +307,7 @@ def test_concat_lazy(self): assert combined.dims == ('z', 'x', 'y') -class TestAutoCombine(object): +class TestAutoCombine: @pytest.mark.parametrize("combine", [_auto_combine_1d, auto_combine]) @requires_dask # only for toolz @@ -425,7 +425,7 @@ def assert_combined_tile_ids_equal(dict1, dict2): assert_equal(dict1[k], dict2[k]) -class TestTileIDsFromNestedList(object): +class TestTileIDsFromNestedList: def test_1d(self): ds = create_test_data input = [ds(0), ds(1)] @@ -533,7 +533,7 @@ def _create_tile_ids(shape): @requires_dask # only for toolz -class TestCombineND(object): +class TestCombineND: @pytest.mark.parametrize("old_id, new_id", [((3, 0, 1), (0, 1)), ((0, 0), (0,)), ((1,), ()), @@ -598,7 +598,7 @@ def test_concat_twice(self, create_combined_ids, concat_dim): assert_equal(result, expected) -class TestCheckShapeTileIDs(object): +class TestCheckShapeTileIDs: def test_check_depths(self): ds = create_test_data(0) combined_tile_ids = {(0,): ds, (0, 1): ds} @@ -616,7 +616,7 @@ def test_check_lengths(self): @requires_dask # only for toolz -class TestAutoCombineND(object): +class TestAutoCombineND: def test_single_dataset(self): objs = [Dataset({'x': [0]}), Dataset({'x': [1]})] actual = auto_combine(objs) @@ -712,7 +712,7 @@ def test_combine_concat_over_redundant_nesting(self): assert_identical(expected, actual) -class TestAutoCombineUsingCoords(object): +class TestAutoCombineUsingCoords: def test_order_inferred_from_coords(self): data = create_test_data() objs = [data.isel(dim2=slice(4, 9)), data.isel(dim2=slice(4))] diff --git a/xarray/tests/test_computation.py b/xarray/tests/test_computation.py index 1003c531018..e3f49fd8d07 100644 --- a/xarray/tests/test_computation.py +++ b/xarray/tests/test_computation.py @@ -42,7 +42,7 @@ def test_signature_properties(): def test_result_name(): - class Named(object): + class Named: def __init__(self, name=None): self.name = name diff --git a/xarray/tests/test_conventions.py b/xarray/tests/test_conventions.py index 27f5e7ec079..b9690c211f4 100644 --- a/xarray/tests/test_conventions.py +++ b/xarray/tests/test_conventions.py @@ -19,7 +19,7 @@ from .test_backends import CFEncodedBase -class TestBoolTypeArray(object): +class TestBoolTypeArray: def test_booltype_array(self): x = np.array([1, 0, 1, 1, 0], dtype='i1') bx = conventions.BoolTypeArray(x) @@ -28,7 +28,7 @@ def test_booltype_array(self): dtype=np.bool)) -class TestNativeEndiannessArray(object): +class TestNativeEndiannessArray: def test(self): x = np.arange(5, dtype='>i8') expected = np.arange(5, dtype='int64') @@ -67,7 +67,7 @@ def test_decode_cf_with_conflicting_fill_missing_value(): @requires_cftime_or_netCDF4 -class TestEncodeCFVariable(object): +class TestEncodeCFVariable: def test_incompatible_attributes(self): invalid_vars = [ Variable(['t'], pd.date_range('2000-01-01', periods=3), @@ -132,7 +132,7 @@ def test_string_object_warning(self): @requires_cftime_or_netCDF4 -class TestDecodeCF(object): +class TestDecodeCF: def test_dataset(self): original = Dataset({ 't': ('t', [0, 1, 2], {'units': 'days since 2000-01-01'}), diff --git a/xarray/tests/test_dask.py b/xarray/tests/test_dask.py index b6a70794c23..0c55fe919d6 100644 --- a/xarray/tests/test_dask.py +++ b/xarray/tests/test_dask.py @@ -22,7 +22,7 @@ dd = pytest.importorskip('dask.dataframe') -class DaskTestCase(object): +class DaskTestCase: def assertLazyAnd(self, expected, actual, test): with (dask.config.set(scheduler='single-threaded') @@ -586,7 +586,7 @@ def test_from_dask_variable(self): self.assertLazyAndIdentical(self.lazy_array, a) -class TestToDaskDataFrame(object): +class TestToDaskDataFrame: def test_to_dask_dataframe(self): # Test conversion of Datasets to dask DataFrames diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index abc0b25be56..25df7defb08 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -23,7 +23,7 @@ requires_scipy, source_ndarray) -class TestDataArray(object): +class TestDataArray: @pytest.fixture(autouse=True) def setup(self): self.attrs = {'attr1': 'value1', 'attr2': 2929} @@ -3809,7 +3809,7 @@ def test_name_in_masking(): assert da.where((da > 5).rename('YokoOno'), drop=True).name == name -class TestIrisConversion(object): +class TestIrisConversion: @requires_iris def test_to_and_from_iris(self): import iris diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 97c1be425a8..30763711701 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -81,7 +81,7 @@ def lazy_inaccessible(k, v): k, v in self._variables.items()) -class TestDataset(object): +class TestDataset: def test_repr(self): data = create_test_data(seed=123) data.attrs['foo'] = 'bar' @@ -267,7 +267,7 @@ def test_constructor_0d(self): actual = Dataset({'x': arg}) assert_identical(expected, actual) - class Arbitrary(object): + class Arbitrary: pass d = pd.Timestamp('2000-01-01T12') diff --git a/xarray/tests/test_duck_array_ops.py b/xarray/tests/test_duck_array_ops.py index 8dfe5bb4468..75ab5f52a1b 100644 --- a/xarray/tests/test_duck_array_ops.py +++ b/xarray/tests/test_duck_array_ops.py @@ -20,7 +20,7 @@ requires_dask) -class TestOps(object): +class TestOps: @pytest.fixture(autouse=True) def setUp(self): diff --git a/xarray/tests/test_extensions.py b/xarray/tests/test_extensions.py index 1b6e665bdae..e67e7a0f6a0 100644 --- a/xarray/tests/test_extensions.py +++ b/xarray/tests/test_extensions.py @@ -9,19 +9,19 @@ @xr.register_dataset_accessor('example_accessor') @xr.register_dataarray_accessor('example_accessor') -class ExampleAccessor(object): +class ExampleAccessor: """For the pickling tests below.""" def __init__(self, xarray_obj): self.obj = xarray_obj -class TestAccessor(object): +class TestAccessor: def test_register(self): @xr.register_dataset_accessor('demo') @xr.register_dataarray_accessor('demo') - class DemoAccessor(object): + class DemoAccessor: """Demo accessor.""" def __init__(self, xarray_obj): @@ -52,7 +52,7 @@ def foo(self): with pytest.warns(Warning, match='overriding a preexisting attribute'): @xr.register_dataarray_accessor('demo') - class Foo(object): + class Foo: pass # it didn't get registered again @@ -80,7 +80,7 @@ def test_broken_accessor(self): # regression test for GH933 @xr.register_dataset_accessor('stupid_accessor') - class BrokenAccessor(object): + class BrokenAccessor: def __init__(self, xarray_obj): raise AttributeError('broken') diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index 7ba48101997..8a3c95a4962 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -10,7 +10,7 @@ from . import raises_regex -class TestFormatting(object): +class TestFormatting: def test_get_indexer_at_least_n_items(self): cases = [ diff --git a/xarray/tests/test_indexing.py b/xarray/tests/test_indexing.py index 14b79c71ca4..9301abb5e32 100644 --- a/xarray/tests/test_indexing.py +++ b/xarray/tests/test_indexing.py @@ -12,7 +12,7 @@ B = IndexerMaker(indexing.BasicIndexer) -class TestIndexers(object): +class TestIndexers: def set_to_zero(self, x, i): x = x.copy() x[i] = 0 @@ -129,7 +129,7 @@ def test_indexer(data, x, expected_pos, expected_idx=None): pd.MultiIndex.from_product([[1, 2], [-1, -2]])) -class TestLazyArray(object): +class TestLazyArray: def test_slice_slice(self): I = ReturnItem() # noqa: E741 # allow ambiguous name for size in [100, 99]: @@ -244,7 +244,7 @@ def check_indexing(v_eager, v_lazy, indexers): check_indexing(v_eager, v_lazy, indexers) -class TestCopyOnWriteArray(object): +class TestCopyOnWriteArray: def test_setitem(self): original = np.arange(10) wrapped = indexing.CopyOnWriteArray(original) @@ -268,7 +268,7 @@ def test_index_scalar(self): assert np.array(x[B[0]][B[()]]) == 'foo' -class TestMemoryCachedArray(object): +class TestMemoryCachedArray: def test_wrapper(self): original = indexing.LazilyOuterIndexedArray(np.arange(10)) wrapped = indexing.MemoryCachedArray(original) @@ -381,7 +381,7 @@ def test_vectorized_indexer(): np.arange(5, dtype=np.int64))) -class Test_vectorized_indexer(object): +class Test_vectorized_indexer: @pytest.fixture(autouse=True) def setup(self): self.data = indexing.NumpyIndexingAdapter(np.random.randn(10, 12, 13)) diff --git a/xarray/tests/test_merge.py b/xarray/tests/test_merge.py index 9c043f4dcfb..0d76db1d1ee 100644 --- a/xarray/tests/test_merge.py +++ b/xarray/tests/test_merge.py @@ -8,7 +8,7 @@ from .test_dataset import create_test_data -class TestMergeInternals(object): +class TestMergeInternals: def test_broadcast_dimension_size(self): actual = merge.broadcast_dimension_size( [xr.Variable('x', [1]), xr.Variable('y', [2, 1])]) @@ -19,11 +19,11 @@ def test_broadcast_dimension_size(self): assert actual == {'x': 1, 'y': 2} with pytest.raises(ValueError): - actual = merge.broadcast_dimension_size( + merge.broadcast_dimension_size( [xr.Variable(('x', 'y'), [[1, 2]]), xr.Variable('y', [2])]) -class TestMergeFunction(object): +class TestMergeFunction: def test_merge_arrays(self): data = create_test_data() actual = xr.merge([data.var1, data.var2]) @@ -128,7 +128,7 @@ def test_merge_no_conflicts_broadcast(self): assert expected.identical(actual) -class TestMergeMethod(object): +class TestMergeMethod: def test_merge(self): data = create_test_data() diff --git a/xarray/tests/test_options.py b/xarray/tests/test_options.py index 1508503f7eb..34bcba58020 100644 --- a/xarray/tests/test_options.py +++ b/xarray/tests/test_options.py @@ -81,7 +81,7 @@ def create_test_dataarray_attrs(seed=0, var='var1'): return da -class TestAttrRetention(object): +class TestAttrRetention: def test_dataset_attr_retention(self): # Use .mean() for all tests: a typical reduction operation ds = create_test_dataset_attrs() diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index c0e03b5791c..5226be0d91d 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -65,7 +65,7 @@ def easy_array(shape, start=0, stop=1): @requires_matplotlib -class PlotTestCase(object): +class PlotTestCase: @pytest.fixture(autouse=True) def setup(self): yield @@ -512,7 +512,7 @@ def test_hist_coord_with_interval(self): @requires_matplotlib -class TestDetermineCmapParams(object): +class TestDetermineCmapParams: @pytest.fixture(autouse=True) def setUp(self): self.data = np.linspace(0, 1, num=100) @@ -706,7 +706,7 @@ def test_norm_sets_vmin_vmax(self): @requires_matplotlib -class TestDiscreteColorMap(object): +class TestDiscreteColorMap: @pytest.fixture(autouse=True) def setUp(self): x = np.arange(start=0, stop=10, step=2) @@ -793,7 +793,7 @@ def test_discrete_colormap_provided_boundary_norm(self): np.testing.assert_allclose(primitive.levels, norm.boundaries) -class Common2dMixin(object): +class Common2dMixin: """ Common tests for 2d plotting go here. @@ -1907,7 +1907,7 @@ def test_plot_seaborn_no_import_warning(): @requires_matplotlib -class TestAxesKwargs(object): +class TestAxesKwargs: @pytest.mark.parametrize('da', test_da_list) @pytest.mark.parametrize('xincrease', [True, False]) def test_xincrease_kwarg(self, da, xincrease): diff --git a/xarray/tests/test_tutorial.py b/xarray/tests/test_tutorial.py index 2bb2cfb0415..841f4f7c832 100644 --- a/xarray/tests/test_tutorial.py +++ b/xarray/tests/test_tutorial.py @@ -9,7 +9,7 @@ @network -class TestLoadDataset(object): +class TestLoadDataset: @pytest.fixture(autouse=True) def setUp(self): self.testfile = 'tiny' diff --git a/xarray/tests/test_ufuncs.py b/xarray/tests/test_ufuncs.py index 2f6ca37bd2a..2c60fb3861e 100644 --- a/xarray/tests/test_ufuncs.py +++ b/xarray/tests/test_ufuncs.py @@ -107,7 +107,7 @@ def test_kwargs(): @requires_np113 def test_xarray_defers_to_unrecognized_type(): - class Other(object): + class Other: def __array_ufunc__(self, *args, **kwargs): return 'other' diff --git a/xarray/tests/test_utils.py b/xarray/tests/test_utils.py index caff78b4fb1..bcd960e4e29 100644 --- a/xarray/tests/test_utils.py +++ b/xarray/tests/test_utils.py @@ -14,7 +14,7 @@ from .test_coding_times import _all_cftime_date_types -class TestAlias(object): +class TestAlias: def test(self): def new_method(): pass @@ -92,7 +92,7 @@ def test_multiindex_from_product_levels_non_unique(): np.testing.assert_array_equal(result.levels[1], [1, 2]) -class TestArrayEquiv(object): +class TestArrayEquiv: def test_0d(self): # verify our work around for pd.isnull not working for 0-dimensional # object arrays @@ -102,7 +102,7 @@ def test_0d(self): assert not duck_array_ops.array_equiv(0, np.array(1, dtype=object)) -class TestDictionaries(object): +class TestDictionaries: @pytest.fixture(autouse=True) def setup(self): self.x = {'a': 'A', 'b': 'B'} @@ -197,7 +197,7 @@ def test_is_grib_path(): assert utils.is_grib_path('example.grb2') -class Test_is_uniform_and_sorted(object): +class Test_is_uniform_and_sorted: def test_sorted_uniform(self): assert utils.is_uniform_spaced(np.arange(5)) @@ -218,7 +218,7 @@ def test_relative_tolerance(self): assert utils.is_uniform_spaced([0, 0.97, 2], rtol=0.1) -class Test_hashable(object): +class Test_hashable: def test_hashable(self): for v in [False, 1, (2, ), (3, 4), 'four']: diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index eec8d268026..4ddd114d767 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -26,7 +26,7 @@ raises_regex, requires_dask, source_ndarray) -class VariableSubclassobjects(object): +class VariableSubclassobjects: def test_properties(self): data = 0.5 * np.arange(10) v = self.cls(['time'], data, {'foo': 'bar'}) @@ -195,7 +195,7 @@ def test_index_0d_not_a_time(self): def test_index_0d_object(self): - class HashableItemWrapper(object): + class HashableItemWrapper: def __init__(self, item): self.item = item @@ -1892,7 +1892,7 @@ def test_coarsen_2d(self): super(TestIndexVariable, self).test_coarsen_2d() -class TestAsCompatibleData(object): +class TestAsCompatibleData: def test_unchanged_types(self): types = (np.asarray, PandasIndexAdapter, LazilyOuterIndexedArray) for t in types: @@ -2033,7 +2033,7 @@ def test_raise_no_warning_for_nan_in_binary_ops(): assert len(record) == 0 -class TestBackendIndexing(object): +class TestBackendIndexing: """ Make sure all the array wrappers can be indexed. """ @pytest.fixture(autouse=True) diff --git a/xarray/ufuncs.py b/xarray/ufuncs.py index dcba208436e..c4261d465e9 100644 --- a/xarray/ufuncs.py +++ b/xarray/ufuncs.py @@ -35,7 +35,7 @@ def _dispatch_priority(obj): return -1 -class _UFuncDispatcher(object): +class _UFuncDispatcher: """Wrapper for dispatching ufuncs.""" def __init__(self, name):