diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 67dd54faf3a..eed39e54395 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -8,6 +8,11 @@ repos: - id: check-yaml - id: debug-statements - id: mixed-line-ending + - repo: https://github.com/MarcoGorelli/absolufy-imports + rev: v0.3.1 + hooks: + - id: absolufy-imports + name: absolufy-imports # This wants to go before isort & flake8 - repo: https://github.com/PyCQA/autoflake rev: "v2.0.0" diff --git a/asv_bench/benchmarks/dataarray_missing.py b/asv_bench/benchmarks/dataarray_missing.py index d786c04e852..124da03eadd 100644 --- a/asv_bench/benchmarks/dataarray_missing.py +++ b/asv_bench/benchmarks/dataarray_missing.py @@ -1,8 +1,7 @@ import pandas as pd import xarray as xr - -from . import parameterized, randn, requires_dask +from asv_bench.benchmarks import parameterized, randn, requires_dask def make_bench_data(shape, frac_nan, chunks): diff --git a/asv_bench/benchmarks/dataset_io.py b/asv_bench/benchmarks/dataset_io.py index 6c2e15c54e9..104551d6858 100644 --- a/asv_bench/benchmarks/dataset_io.py +++ b/asv_bench/benchmarks/dataset_io.py @@ -4,8 +4,7 @@ import pandas as pd import xarray as xr - -from . import _skip_slow, randint, randn, requires_dask +from asv_bench.benchmarks import _skip_slow, randint, randn, requires_dask try: import dask diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 490c2ccbd4c..e9176dc934f 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -2,8 +2,7 @@ import pandas as pd import xarray as xr - -from . import _skip_slow, parameterized, requires_dask +from asv_bench.benchmarks import _skip_slow, parameterized, requires_dask class GroupBy: diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 15212ec0c61..91881f246bd 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -4,8 +4,7 @@ import pandas as pd import xarray as xr - -from . import parameterized, randint, randn, requires_dask +from asv_bench.benchmarks import parameterized, randint, randn, requires_dask nx = 2000 ny = 1000 diff --git a/asv_bench/benchmarks/interp.py b/asv_bench/benchmarks/interp.py index 4b6691bcc0a..5ca2df2ec1c 100644 --- a/asv_bench/benchmarks/interp.py +++ b/asv_bench/benchmarks/interp.py @@ -2,8 +2,7 @@ import pandas as pd import xarray as xr - -from . import parameterized, randn, requires_dask +from asv_bench.benchmarks import parameterized, randn, requires_dask nx = 1500 ny = 1000 diff --git a/asv_bench/benchmarks/pandas.py b/asv_bench/benchmarks/pandas.py index 8aaa515d417..05b1991a808 100644 --- a/asv_bench/benchmarks/pandas.py +++ b/asv_bench/benchmarks/pandas.py @@ -2,8 +2,7 @@ import pandas as pd import xarray as xr - -from . import parameterized +from asv_bench.benchmarks import parameterized class MultiIndexSeries: diff --git a/asv_bench/benchmarks/polyfit.py b/asv_bench/benchmarks/polyfit.py index 429ffa19baa..610dbf208eb 100644 --- a/asv_bench/benchmarks/polyfit.py +++ b/asv_bench/benchmarks/polyfit.py @@ -1,8 +1,7 @@ import numpy as np import xarray as xr - -from . import parameterized, randn, requires_dask +from asv_bench.benchmarks import parameterized, randn, requires_dask NDEGS = (2, 5, 20) NX = (10**2, 10**6) diff --git a/asv_bench/benchmarks/reindexing.py b/asv_bench/benchmarks/reindexing.py index 9d0767fc3b3..644480e48e8 100644 --- a/asv_bench/benchmarks/reindexing.py +++ b/asv_bench/benchmarks/reindexing.py @@ -1,8 +1,7 @@ import numpy as np import xarray as xr - -from . import requires_dask +from asv_bench.benchmarks import requires_dask ntime = 500 nx = 50 diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index 1d3713f19bf..d4fb0b20070 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -2,8 +2,7 @@ import pandas as pd import xarray as xr - -from . import parameterized, randn, requires_dask +from asv_bench.benchmarks import parameterized, randn, requires_dask nx = 300 long_nx = 30000 diff --git a/asv_bench/benchmarks/unstacking.py b/asv_bench/benchmarks/unstacking.py index dc8bc3307c3..33158350bd4 100644 --- a/asv_bench/benchmarks/unstacking.py +++ b/asv_bench/benchmarks/unstacking.py @@ -2,8 +2,7 @@ import pandas as pd import xarray as xr - -from . import requires_dask, requires_sparse +from asv_bench.benchmarks import requires_dask, requires_sparse class Unstacking: diff --git a/doc/whats-new.rst b/doc/whats-new.rst index c28812b100e..b66a0239fd3 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -42,7 +42,9 @@ Documentation Internal Changes ~~~~~~~~~~~~~~~~ - +- Add the pre-commit hook `absolufy-imports` to convert relative xarray imports to + absolute imports (:pull:`7204`). + By `Jimmy Westling `_. .. _whats-new.2022.12.0: diff --git a/xarray/__init__.py b/xarray/__init__.py index e920e94ca19..d064502c20b 100644 --- a/xarray/__init__.py +++ b/xarray/__init__.py @@ -1,5 +1,5 @@ -from . import testing, tutorial -from .backends.api import ( +from xarray import testing, tutorial +from xarray.backends.api import ( load_dataarray, load_dataset, open_dataarray, @@ -7,16 +7,16 @@ open_mfdataset, save_mfdataset, ) -from .backends.rasterio_ import open_rasterio -from .backends.zarr import open_zarr -from .coding.cftime_offsets import cftime_range, date_range, date_range_like -from .coding.cftimeindex import CFTimeIndex -from .coding.frequencies import infer_freq -from .conventions import SerializationWarning, decode_cf -from .core.alignment import align, broadcast -from .core.combine import combine_by_coords, combine_nested -from .core.common import ALL_DIMS, full_like, ones_like, zeros_like -from .core.computation import ( +from xarray.backends.rasterio_ import open_rasterio +from xarray.backends.zarr import open_zarr +from xarray.coding.cftime_offsets import cftime_range, date_range, date_range_like +from xarray.coding.cftimeindex import CFTimeIndex +from xarray.coding.frequencies import infer_freq +from xarray.conventions import SerializationWarning, decode_cf +from xarray.core.alignment import align, broadcast +from xarray.core.combine import combine_by_coords, combine_nested +from xarray.core.common import ALL_DIMS, full_like, ones_like, zeros_like +from xarray.core.computation import ( apply_ufunc, corr, cov, @@ -26,15 +26,18 @@ unify_chunks, where, ) -from .core.concat import concat -from .core.dataarray import DataArray -from .core.dataset import Dataset -from .core.extensions import register_dataarray_accessor, register_dataset_accessor -from .core.merge import Context, MergeError, merge -from .core.options import get_options, set_options -from .core.parallel import map_blocks -from .core.variable import Coordinate, IndexVariable, Variable, as_variable -from .util.print_versions import show_versions +from xarray.core.concat import concat +from xarray.core.dataarray import DataArray +from xarray.core.dataset import Dataset +from xarray.core.extensions import ( + register_dataarray_accessor, + register_dataset_accessor, +) +from xarray.core.merge import Context, MergeError, merge +from xarray.core.options import get_options, set_options +from xarray.core.parallel import map_blocks +from xarray.core.variable import Coordinate, IndexVariable, Variable, as_variable +from xarray.util.print_versions import show_versions try: from importlib.metadata import version as _version diff --git a/xarray/backends/__init__.py b/xarray/backends/__init__.py index c81d7860366..302d89335dd 100644 --- a/xarray/backends/__init__.py +++ b/xarray/backends/__init__.py @@ -3,19 +3,26 @@ 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 .cfgrib_ import CfGribDataStore -from .common import AbstractDataStore, BackendArray, BackendEntrypoint -from .file_manager import CachingFileManager, DummyFileManager, FileManager -from .h5netcdf_ import H5netcdfBackendEntrypoint, H5NetCDFStore -from .memory import InMemoryDataStore -from .netCDF4_ import NetCDF4BackendEntrypoint, NetCDF4DataStore -from .plugins import list_engines -from .pseudonetcdf_ import PseudoNetCDFBackendEntrypoint, PseudoNetCDFDataStore -from .pydap_ import PydapBackendEntrypoint, PydapDataStore -from .pynio_ import NioDataStore -from .scipy_ import ScipyBackendEntrypoint, ScipyDataStore -from .store import StoreBackendEntrypoint -from .zarr import ZarrBackendEntrypoint, ZarrStore +from xarray.backends.cfgrib_ import CfGribDataStore +from xarray.backends.common import AbstractDataStore, BackendArray, BackendEntrypoint +from xarray.backends.file_manager import ( + CachingFileManager, + DummyFileManager, + FileManager, +) +from xarray.backends.h5netcdf_ import H5netcdfBackendEntrypoint, H5NetCDFStore +from xarray.backends.memory import InMemoryDataStore +from xarray.backends.netCDF4_ import NetCDF4BackendEntrypoint, NetCDF4DataStore +from xarray.backends.plugins import list_engines +from xarray.backends.pseudonetcdf_ import ( + PseudoNetCDFBackendEntrypoint, + PseudoNetCDFDataStore, +) +from xarray.backends.pydap_ import PydapBackendEntrypoint, PydapDataStore +from xarray.backends.pynio_ import NioDataStore +from xarray.backends.scipy_ import ScipyBackendEntrypoint, ScipyDataStore +from xarray.backends.store import StoreBackendEntrypoint +from xarray.backends.zarr import ZarrBackendEntrypoint, ZarrStore __all__ = [ "AbstractDataStore", diff --git a/xarray/backends/api.py b/xarray/backends/api.py index 02cf425386b..1f1ff0711aa 100644 --- a/xarray/backends/api.py +++ b/xarray/backends/api.py @@ -25,20 +25,20 @@ import numpy as np -from .. import backends, conventions -from ..core import indexing -from ..core.combine import ( +from xarray import backends, conventions +from xarray.backends import plugins +from xarray.backends.common import AbstractDataStore, ArrayWriter, _normalize_path +from xarray.backends.locks import _get_scheduler +from xarray.core import indexing +from xarray.core.combine import ( _infer_concat_order_from_positions, _nested_combine, combine_by_coords, ) -from ..core.dataarray import DataArray -from ..core.dataset import Dataset, _get_chunk, _maybe_chunk -from ..core.indexes import Index -from ..core.utils import is_remote_uri -from . import plugins -from .common import AbstractDataStore, ArrayWriter, _normalize_path -from .locks import _get_scheduler +from xarray.core.dataarray import DataArray +from xarray.core.dataset import Dataset, _get_chunk, _maybe_chunk +from xarray.core.indexes import Index +from xarray.core.utils import is_remote_uri if TYPE_CHECKING: try: @@ -47,13 +47,13 @@ Delayed = None # type: ignore from io import BufferedIOBase - from ..core.types import ( + from xarray.backends.common import BackendEntrypoint + from xarray.core.types import ( CombineAttrsOptions, CompatOptions, JoinOptions, NestedSequence, ) - from .common import BackendEntrypoint T_NetcdfEngine = Literal["netcdf4", "scipy", "h5netcdf"] T_Engine = Union[ diff --git a/xarray/backends/cfgrib_.py b/xarray/backends/cfgrib_.py index 6944d08a71d..4ab4c73ed07 100644 --- a/xarray/backends/cfgrib_.py +++ b/xarray/backends/cfgrib_.py @@ -5,18 +5,18 @@ import numpy as np -from ..core import indexing -from ..core.utils import Frozen, FrozenDict, close_on_error, module_available -from ..core.variable import Variable -from .common import ( +from xarray.backends.common import ( BACKEND_ENTRYPOINTS, AbstractDataStore, BackendArray, BackendEntrypoint, _normalize_path, ) -from .locks import SerializableLock, ensure_lock -from .store import StoreBackendEntrypoint +from xarray.backends.locks import SerializableLock, ensure_lock +from xarray.backends.store import StoreBackendEntrypoint +from xarray.core import indexing +from xarray.core.utils import Frozen, FrozenDict, close_on_error, module_available +from xarray.core.variable import Variable # FIXME: Add a dedicated lock, even if ecCodes is supposed to be thread-safe # in most circumstances. See: diff --git a/xarray/backends/common.py b/xarray/backends/common.py index 02419e7f68d..47b50ddc064 100644 --- a/xarray/backends/common.py +++ b/xarray/backends/common.py @@ -8,10 +8,10 @@ import numpy as np -from ..conventions import cf_encoder -from ..core import indexing -from ..core.pycompat import is_duck_dask_array -from ..core.utils import FrozenDict, NdimSizeLenMixin, is_remote_uri +from xarray.conventions import cf_encoder +from xarray.core import indexing +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.utils import FrozenDict, NdimSizeLenMixin, is_remote_uri if TYPE_CHECKING: from io import BufferedIOBase diff --git a/xarray/backends/file_manager.py b/xarray/backends/file_manager.py index b09a6aa39bd..478419b9bbb 100644 --- a/xarray/backends/file_manager.py +++ b/xarray/backends/file_manager.py @@ -7,10 +7,10 @@ import warnings from typing import Any, Hashable -from ..core import utils -from ..core.options import OPTIONS -from .locks import acquire -from .lru_cache import LRUCache +from xarray.backends.locks import acquire +from xarray.backends.lru_cache import LRUCache +from xarray.core import utils +from xarray.core.options import OPTIONS # Global cache for storing open files. FILE_CACHE: LRUCache[Any, io.IOBase] = LRUCache( diff --git a/xarray/backends/h5netcdf_.py b/xarray/backends/h5netcdf_.py index 6a6f54704ac..69acd6202c1 100644 --- a/xarray/backends/h5netcdf_.py +++ b/xarray/backends/h5netcdf_.py @@ -6,32 +6,32 @@ from packaging.version import Version -from ..core import indexing -from ..core.utils import ( - FrozenDict, - is_remote_uri, - module_available, - read_magic_number_from_file, - try_read_magic_number_from_file_or_path, -) -from ..core.variable import Variable -from .common import ( +from xarray.backends.common import ( BACKEND_ENTRYPOINTS, BackendEntrypoint, WritableCFDataStore, _normalize_path, find_root_and_group, ) -from .file_manager import CachingFileManager, DummyFileManager -from .locks import HDF5_LOCK, combine_locks, ensure_lock, get_write_lock -from .netCDF4_ import ( +from xarray.backends.file_manager import CachingFileManager, DummyFileManager +from xarray.backends.locks import HDF5_LOCK, combine_locks, ensure_lock, get_write_lock +from xarray.backends.netCDF4_ import ( BaseNetCDF4Array, _encode_nc4_variable, _extract_nc4_variable_encoding, _get_datatype, _nc4_require_group, ) -from .store import StoreBackendEntrypoint +from xarray.backends.store import StoreBackendEntrypoint +from xarray.core import indexing +from xarray.core.utils import ( + FrozenDict, + is_remote_uri, + module_available, + read_magic_number_from_file, + try_read_magic_number_from_file_or_path, +) +from xarray.core.variable import Variable class H5NetCDFArrayWrapper(BaseNetCDF4Array): diff --git a/xarray/backends/memory.py b/xarray/backends/memory.py index 6b00a78dd64..9df6701d954 100644 --- a/xarray/backends/memory.py +++ b/xarray/backends/memory.py @@ -4,8 +4,8 @@ import numpy as np -from ..core.variable import Variable -from .common import AbstractWritableDataStore +from xarray.backends.common import AbstractWritableDataStore +from xarray.core.variable import Variable class InMemoryDataStore(AbstractWritableDataStore): diff --git a/xarray/backends/netCDF4_.py b/xarray/backends/netCDF4_.py index f8b3192a4b9..f1ca560dee1 100644 --- a/xarray/backends/netCDF4_.py +++ b/xarray/backends/netCDF4_.py @@ -7,18 +7,8 @@ import numpy as np -from .. import coding -from ..coding.variables import pop_to -from ..core import indexing -from ..core.utils import ( - FrozenDict, - close_on_error, - is_remote_uri, - module_available, - try_read_magic_number_from_path, -) -from ..core.variable import Variable -from .common import ( +from xarray import coding +from xarray.backends.common import ( BACKEND_ENTRYPOINTS, BackendArray, BackendEntrypoint, @@ -27,10 +17,26 @@ find_root_and_group, robust_getitem, ) -from .file_manager import CachingFileManager, DummyFileManager -from .locks import HDF5_LOCK, NETCDFC_LOCK, combine_locks, ensure_lock, get_write_lock -from .netcdf3 import encode_nc3_attr_value, encode_nc3_variable -from .store import StoreBackendEntrypoint +from xarray.backends.file_manager import CachingFileManager, DummyFileManager +from xarray.backends.locks import ( + HDF5_LOCK, + NETCDFC_LOCK, + combine_locks, + ensure_lock, + get_write_lock, +) +from xarray.backends.netcdf3 import encode_nc3_attr_value, encode_nc3_variable +from xarray.backends.store import StoreBackendEntrypoint +from xarray.coding.variables import pop_to +from xarray.core import indexing +from xarray.core.utils import ( + FrozenDict, + close_on_error, + is_remote_uri, + module_available, + try_read_magic_number_from_path, +) +from xarray.core.variable import Variable # This lookup table maps from dtype.byteorder to a readable endian # string used by netCDF4. diff --git a/xarray/backends/netcdf3.py b/xarray/backends/netcdf3.py index 572962f7ad5..ef389eefc90 100644 --- a/xarray/backends/netcdf3.py +++ b/xarray/backends/netcdf3.py @@ -4,8 +4,8 @@ import numpy as np -from .. import coding -from ..core.variable import Variable +from xarray import coding +from xarray.core.variable import Variable # Special characters that are permitted in netCDF names except in the # 0th position of the string diff --git a/xarray/backends/plugins.py b/xarray/backends/plugins.py index 374383f55c8..bae1dcd2225 100644 --- a/xarray/backends/plugins.py +++ b/xarray/backends/plugins.py @@ -8,13 +8,13 @@ from importlib.metadata import entry_points from typing import TYPE_CHECKING, Any -from .common import BACKEND_ENTRYPOINTS, BackendEntrypoint +from xarray.backends.common import BACKEND_ENTRYPOINTS, BackendEntrypoint if TYPE_CHECKING: import os from io import BufferedIOBase - from .common import AbstractDataStore + from xarray.backends.common import AbstractDataStore STANDARD_BACKENDS_ORDER = ["netcdf4", "h5netcdf", "scipy"] diff --git a/xarray/backends/pseudonetcdf_.py b/xarray/backends/pseudonetcdf_.py index ae1b976bb2c..fc8bf2c81b3 100644 --- a/xarray/backends/pseudonetcdf_.py +++ b/xarray/backends/pseudonetcdf_.py @@ -2,19 +2,19 @@ import numpy as np -from ..core import indexing -from ..core.utils import Frozen, FrozenDict, close_on_error, module_available -from ..core.variable import Variable -from .common import ( +from xarray.backends.common import ( BACKEND_ENTRYPOINTS, AbstractDataStore, BackendArray, BackendEntrypoint, _normalize_path, ) -from .file_manager import CachingFileManager -from .locks import HDF5_LOCK, NETCDFC_LOCK, combine_locks, ensure_lock -from .store import StoreBackendEntrypoint +from xarray.backends.file_manager import CachingFileManager +from xarray.backends.locks import HDF5_LOCK, NETCDFC_LOCK, combine_locks, ensure_lock +from xarray.backends.store import StoreBackendEntrypoint +from xarray.core import indexing +from xarray.core.utils import Frozen, FrozenDict, close_on_error, module_available +from xarray.core.variable import Variable # psuedonetcdf can invoke netCDF libraries internally PNETCDF_LOCK = combine_locks([HDF5_LOCK, NETCDFC_LOCK]) diff --git a/xarray/backends/pydap_.py b/xarray/backends/pydap_.py index 3dfb662a939..cba31d7e697 100644 --- a/xarray/backends/pydap_.py +++ b/xarray/backends/pydap_.py @@ -3,9 +3,17 @@ import numpy as np from packaging.version import Version -from ..core import indexing -from ..core.pycompat import integer_types -from ..core.utils import ( +from xarray.backends.common import ( + BACKEND_ENTRYPOINTS, + AbstractDataStore, + BackendArray, + BackendEntrypoint, + robust_getitem, +) +from xarray.backends.store import StoreBackendEntrypoint +from xarray.core import indexing +from xarray.core.pycompat import integer_types +from xarray.core.utils import ( Frozen, FrozenDict, close_on_error, @@ -13,15 +21,7 @@ is_remote_uri, module_available, ) -from ..core.variable import Variable -from .common import ( - BACKEND_ENTRYPOINTS, - AbstractDataStore, - BackendArray, - BackendEntrypoint, - robust_getitem, -) -from .store import StoreBackendEntrypoint +from xarray.core.variable import Variable class PydapArrayWrapper(BackendArray): diff --git a/xarray/backends/pynio_.py b/xarray/backends/pynio_.py index cb7c65c0432..611ea978990 100644 --- a/xarray/backends/pynio_.py +++ b/xarray/backends/pynio_.py @@ -4,19 +4,25 @@ import numpy as np -from ..core import indexing -from ..core.utils import Frozen, FrozenDict, close_on_error, module_available -from ..core.variable import Variable -from .common import ( +from xarray.backends.common import ( BACKEND_ENTRYPOINTS, AbstractDataStore, BackendArray, BackendEntrypoint, _normalize_path, ) -from .file_manager import CachingFileManager -from .locks import HDF5_LOCK, NETCDFC_LOCK, SerializableLock, combine_locks, ensure_lock -from .store import StoreBackendEntrypoint +from xarray.backends.file_manager import CachingFileManager +from xarray.backends.locks import ( + HDF5_LOCK, + NETCDFC_LOCK, + SerializableLock, + combine_locks, + ensure_lock, +) +from xarray.backends.store import StoreBackendEntrypoint +from xarray.core import indexing +from xarray.core.utils import Frozen, FrozenDict, close_on_error, module_available +from xarray.core.variable import Variable # PyNIO can invoke netCDF libraries internally # Add a dedicated lock just in case NCL as well isn't thread-safe. diff --git a/xarray/backends/rasterio_.py b/xarray/backends/rasterio_.py index acd9070320b..15006dee5f1 100644 --- a/xarray/backends/rasterio_.py +++ b/xarray/backends/rasterio_.py @@ -5,12 +5,12 @@ import numpy as np -from ..core import indexing -from ..core.dataarray import DataArray -from ..core.utils import is_scalar -from .common import BackendArray -from .file_manager import CachingFileManager -from .locks import SerializableLock +from xarray.backends.common import BackendArray +from xarray.backends.file_manager import CachingFileManager +from xarray.backends.locks import SerializableLock +from xarray.core import indexing +from xarray.core.dataarray import DataArray +from xarray.core.utils import is_scalar # TODO: should this be GDAL_LOCK instead? RASTERIO_LOCK = SerializableLock() diff --git a/xarray/backends/scipy_.py b/xarray/backends/scipy_.py index 3f852d0d03c..12f88b02f47 100644 --- a/xarray/backends/scipy_.py +++ b/xarray/backends/scipy_.py @@ -6,26 +6,30 @@ import numpy as np -from ..core.indexing import NumpyIndexingAdapter -from ..core.utils import ( - Frozen, - FrozenDict, - close_on_error, - module_available, - try_read_magic_number_from_file_or_path, -) -from ..core.variable import Variable -from .common import ( +from xarray.backends.common import ( BACKEND_ENTRYPOINTS, BackendArray, BackendEntrypoint, WritableCFDataStore, _normalize_path, ) -from .file_manager import CachingFileManager, DummyFileManager -from .locks import ensure_lock, get_write_lock -from .netcdf3 import encode_nc3_attr_value, encode_nc3_variable, is_valid_nc3_name -from .store import StoreBackendEntrypoint +from xarray.backends.file_manager import CachingFileManager, DummyFileManager +from xarray.backends.locks import ensure_lock, get_write_lock +from xarray.backends.netcdf3 import ( + encode_nc3_attr_value, + encode_nc3_variable, + is_valid_nc3_name, +) +from xarray.backends.store import StoreBackendEntrypoint +from xarray.core.indexing import NumpyIndexingAdapter +from xarray.core.utils import ( + Frozen, + FrozenDict, + close_on_error, + module_available, + try_read_magic_number_from_file_or_path, +) +from xarray.core.variable import Variable def _decode_string(s): diff --git a/xarray/backends/store.py b/xarray/backends/store.py index c2b402bb7c2..1f7a44bf4dc 100644 --- a/xarray/backends/store.py +++ b/xarray/backends/store.py @@ -1,8 +1,12 @@ from __future__ import annotations -from .. import conventions -from ..core.dataset import Dataset -from .common import BACKEND_ENTRYPOINTS, AbstractDataStore, BackendEntrypoint +from xarray import conventions +from xarray.backends.common import ( + BACKEND_ENTRYPOINTS, + AbstractDataStore, + BackendEntrypoint, +) +from xarray.core.dataset import Dataset class StoreBackendEntrypoint(BackendEntrypoint): diff --git a/xarray/backends/zarr.py b/xarray/backends/zarr.py index cca2d89678f..e30e7e9f4d8 100644 --- a/xarray/backends/zarr.py +++ b/xarray/backends/zarr.py @@ -6,12 +6,8 @@ import numpy as np -from .. import coding, conventions -from ..core import indexing -from ..core.pycompat import integer_types -from ..core.utils import FrozenDict, HiddenKeyDict, close_on_error, module_available -from ..core.variable import Variable -from .common import ( +from xarray import coding, conventions +from xarray.backends.common import ( BACKEND_ENTRYPOINTS, AbstractWritableDataStore, BackendArray, @@ -19,7 +15,16 @@ _encode_variable_name, _normalize_path, ) -from .store import StoreBackendEntrypoint +from xarray.backends.store import StoreBackendEntrypoint +from xarray.core import indexing +from xarray.core.pycompat import integer_types +from xarray.core.utils import ( + FrozenDict, + HiddenKeyDict, + close_on_error, + module_available, +) +from xarray.core.variable import Variable # need some special secret attributes to tell us the dimensions DIMENSION_KEY = "_ARRAY_DIMENSIONS" @@ -791,7 +796,7 @@ def open_zarr( ---------- http://zarr.readthedocs.io/ """ - from .api import open_dataset + from xarray.backends.api import open_dataset if chunks == "auto": try: diff --git a/xarray/coding/calendar_ops.py b/xarray/coding/calendar_ops.py index 04e46e942a1..06f57757619 100644 --- a/xarray/coding/calendar_ops.py +++ b/xarray/coding/calendar_ops.py @@ -3,10 +3,10 @@ import numpy as np import pandas as pd -from ..core.common import _contains_datetime_like_objects, is_np_datetime_like -from .cftime_offsets import date_range_like, get_date_type -from .cftimeindex import CFTimeIndex -from .times import _should_cftime_be_used, convert_times +from xarray.coding.cftime_offsets import date_range_like, get_date_type +from xarray.coding.cftimeindex import CFTimeIndex +from xarray.coding.times import _should_cftime_be_used, convert_times +from xarray.core.common import _contains_datetime_like_objects, is_np_datetime_like try: import cftime @@ -144,7 +144,7 @@ def convert_calendar( This option is best used with data on a frequency coarser than daily. """ - from ..core.dataarray import DataArray + from xarray.core.dataarray import DataArray time = obj[dim] if not _contains_datetime_like_objects(time): @@ -265,7 +265,7 @@ def _datetime_to_decimal_year(times, dim="time", calendar=None): Ex: '2000-03-01 12:00' is 2000.1653 in a standard calendar, 2000.16301 in a "noleap" or 2000.16806 in a "360_day". """ - from ..core.dataarray import DataArray + from xarray.core.dataarray import DataArray calendar = calendar or times.dt.calendar @@ -313,7 +313,7 @@ def interp_calendar(source, target, dim="time"): DataArray or Dataset The source interpolated on the decimal years of target, """ - from ..core.dataarray import DataArray + from xarray.core.dataarray import DataArray if isinstance(target, (pd.DatetimeIndex, CFTimeIndex)): target = DataArray(target, dims=(dim,), name=dim) diff --git a/xarray/coding/cftime_offsets.py b/xarray/coding/cftime_offsets.py index 04b2d773e2e..801fbbf7052 100644 --- a/xarray/coding/cftime_offsets.py +++ b/xarray/coding/cftime_offsets.py @@ -49,15 +49,15 @@ import numpy as np import pandas as pd -from ..core.common import _contains_datetime_like_objects, is_np_datetime_like -from ..core.pdcompat import count_not_none -from .cftimeindex import CFTimeIndex, _parse_iso8601_with_reso -from .times import ( +from xarray.coding.cftimeindex import CFTimeIndex, _parse_iso8601_with_reso +from xarray.coding.times import ( _is_standard_calendar, _should_cftime_be_used, convert_time_or_go_back, format_cftime_datetime, ) +from xarray.core.common import _contains_datetime_like_objects, is_np_datetime_like +from xarray.core.pdcompat import count_not_none try: import cftime @@ -1124,7 +1124,7 @@ def date_range( cftime_range date_range_like """ - from .times import _is_standard_calendar + from xarray.coding.times import _is_standard_calendar if tz is not None: use_cftime = False @@ -1189,8 +1189,8 @@ def date_range_like(source, calendar, use_cftime=None): last day of the month. Then the output range will also end on the last day of the month in the new calendar. """ - from ..core.dataarray import DataArray - from .frequencies import infer_freq + from xarray.coding.frequencies import infer_freq + from xarray.core.dataarray import DataArray if not isinstance(source, (pd.DatetimeIndex, CFTimeIndex)) and ( isinstance(source, DataArray) diff --git a/xarray/coding/cftimeindex.py b/xarray/coding/cftimeindex.py index f1c195fd5eb..7561ccb6733 100644 --- a/xarray/coding/cftimeindex.py +++ b/xarray/coding/cftimeindex.py @@ -49,12 +49,15 @@ import pandas as pd from packaging.version import Version +from xarray.coding.times import ( + _STANDARD_CALENDARS, + cftime_to_nptime, + infer_calendar_name, +) +from xarray.core.common import _contains_cftime_datetimes +from xarray.core.options import OPTIONS from xarray.core.utils import is_scalar -from ..core.common import _contains_cftime_datetimes -from ..core.options import OPTIONS -from .times import _STANDARD_CALENDARS, cftime_to_nptime, infer_calendar_name - try: import cftime except ImportError: @@ -549,7 +552,7 @@ def shift(self, n: int | float, freq: str | timedelta): if isinstance(freq, timedelta): return self + n * freq elif isinstance(freq, str): - from .cftime_offsets import to_offset + from xarray.coding.cftime_offsets import to_offset return self + n * to_offset(freq) else: @@ -679,7 +682,7 @@ def strftime(self, date_format): @property def asi8(self): """Convert to integers with units of microseconds since 1970-01-01.""" - from ..core.resample_cftime import exact_cftime_datetime_difference + from xarray.core.resample_cftime import exact_cftime_datetime_difference epoch = self.date_type(1970, 1, 1) return np.array( @@ -693,20 +696,20 @@ def asi8(self): @property def calendar(self): """The calendar used by the datetimes in the index.""" - from .times import infer_calendar_name + from xarray.coding.times import infer_calendar_name return infer_calendar_name(self) @property def freq(self): """The frequency used by the dates in the index.""" - from .frequencies import infer_freq + from xarray.coding.frequencies import infer_freq return infer_freq(self) def _round_via_method(self, freq, method): """Round dates using a specified method.""" - from .cftime_offsets import CFTIME_TICKS, to_offset + from xarray.coding.cftime_offsets import CFTIME_TICKS, to_offset offset = to_offset(freq) if not isinstance(offset, CFTIME_TICKS): diff --git a/xarray/coding/frequencies.py b/xarray/coding/frequencies.py index c43f39f1cc3..fef2f5a8319 100644 --- a/xarray/coding/frequencies.py +++ b/xarray/coding/frequencies.py @@ -44,9 +44,9 @@ import numpy as np import pandas as pd -from ..core.common import _contains_datetime_like_objects -from .cftime_offsets import _MONTH_ABBREVIATIONS -from .cftimeindex import CFTimeIndex +from xarray.coding.cftime_offsets import _MONTH_ABBREVIATIONS +from xarray.coding.cftimeindex import CFTimeIndex +from xarray.core.common import _contains_datetime_like_objects _ONE_MICRO = 1 _ONE_MILLI = _ONE_MICRO * 1000 diff --git a/xarray/coding/strings.py b/xarray/coding/strings.py index 231dc8a9f8f..61b3ab7c46c 100644 --- a/xarray/coding/strings.py +++ b/xarray/coding/strings.py @@ -5,10 +5,7 @@ import numpy as np -from ..core import indexing -from ..core.pycompat import is_duck_dask_array -from ..core.variable import Variable -from .variables import ( +from xarray.coding.variables import ( VariableCoder, lazy_elemwise_func, pop_to, @@ -16,6 +13,9 @@ unpack_for_decoding, unpack_for_encoding, ) +from xarray.core import indexing +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.variable import Variable def create_vlen_dtype(element_type): diff --git a/xarray/coding/times.py b/xarray/coding/times.py index 332e73e486c..b5d553df2c7 100644 --- a/xarray/coding/times.py +++ b/xarray/coding/times.py @@ -10,12 +10,7 @@ import pandas as pd from pandas.errors import OutOfBoundsDatetime, OutOfBoundsTimedelta -from ..core import indexing -from ..core.common import contains_cftime_datetimes, is_np_datetime_like -from ..core.formatting import first_n_items, format_timestamp, last_item -from ..core.pycompat import is_duck_dask_array -from ..core.variable import Variable -from .variables import ( +from xarray.coding.variables import ( SerializationWarning, VariableCoder, lazy_elemwise_func, @@ -24,6 +19,11 @@ unpack_for_decoding, unpack_for_encoding, ) +from xarray.core import indexing +from xarray.core.common import contains_cftime_datetimes, is_np_datetime_like +from xarray.core.formatting import first_n_items, format_timestamp, last_item +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.variable import Variable try: import cftime @@ -31,7 +31,7 @@ cftime = None if TYPE_CHECKING: - from ..core.types import CFCalendar + from xarray.core.types import CFCalendar # standard calendars recognized by cftime _STANDARD_CALENDARS = {"standard", "gregorian", "proleptic_gregorian"} diff --git a/xarray/coding/variables.py b/xarray/coding/variables.py index 8af41048fb6..286c44a3274 100644 --- a/xarray/coding/variables.py +++ b/xarray/coding/variables.py @@ -8,9 +8,9 @@ import numpy as np import pandas as pd -from ..core import dtypes, duck_array_ops, indexing -from ..core.pycompat import is_duck_dask_array -from ..core.variable import Variable +from xarray.core import dtypes, duck_array_ops, indexing +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.variable import Variable class SerializationWarning(RuntimeWarning): diff --git a/xarray/conventions.py b/xarray/conventions.py index 695bed3b365..082c20c6b62 100644 --- a/xarray/conventions.py +++ b/xarray/conventions.py @@ -4,12 +4,15 @@ import numpy as np import pandas as pd -from .coding import strings, times, variables -from .coding.variables import SerializationWarning, pop_to -from .core import duck_array_ops, indexing -from .core.common import _contains_datetime_like_objects, contains_cftime_datetimes -from .core.pycompat import is_duck_dask_array -from .core.variable import IndexVariable, Variable, as_variable +from xarray.coding import strings, times, variables +from xarray.coding.variables import SerializationWarning, pop_to +from xarray.core import duck_array_ops, indexing +from xarray.core.common import ( + _contains_datetime_like_objects, + contains_cftime_datetimes, +) +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.variable import IndexVariable, Variable, as_variable CF_RELATED_DATA = ( "bounds", @@ -639,8 +642,8 @@ def decode_cf( ------- decoded : Dataset """ - from .backends.common import AbstractDataStore - from .core.dataset import Dataset + from xarray.backends.common import AbstractDataStore + from xarray.core.dataset import Dataset if isinstance(obj, Dataset): vars = obj._variables diff --git a/xarray/convert.py b/xarray/convert.py index 5702bca1deb..629f18ed6b9 100644 --- a/xarray/convert.py +++ b/xarray/convert.py @@ -5,12 +5,12 @@ import numpy as np import pandas as pd -from .coding.times import CFDatetimeCoder, CFTimedeltaCoder -from .conventions import decode_cf -from .core import duck_array_ops -from .core.dataarray import DataArray -from .core.dtypes import get_fill_value -from .core.pycompat import array_type +from xarray.coding.times import CFDatetimeCoder, CFTimedeltaCoder +from xarray.conventions import decode_cf +from xarray.core import duck_array_ops +from xarray.core.dataarray import DataArray +from xarray.core.dtypes import get_fill_value +from xarray.core.pycompat import array_type cdms2_ignored_attrs = {"name", "tileIndex"} iris_forbidden_keys = { diff --git a/xarray/core/_aggregations.py b/xarray/core/_aggregations.py index 1db330fb76f..34732810b24 100644 --- a/xarray/core/_aggregations.py +++ b/xarray/core/_aggregations.py @@ -5,14 +5,14 @@ from typing import TYPE_CHECKING, Any, Callable, Sequence -from . import duck_array_ops -from .options import OPTIONS -from .types import Dims -from .utils import contains_only_dask_or_numpy, module_available +from xarray.core import duck_array_ops +from xarray.core.options import OPTIONS +from xarray.core.types import Dims +from xarray.core.utils import contains_only_dask_or_numpy, module_available if TYPE_CHECKING: - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset flox_available = module_available("flox") diff --git a/xarray/core/_typed_ops.py b/xarray/core/_typed_ops.py index d1e68a6fc0d..a6e6fdbfaec 100644 --- a/xarray/core/_typed_ops.py +++ b/xarray/core/_typed_ops.py @@ -3,7 +3,7 @@ import operator -from . import nputils, ops +from xarray.core import nputils, ops class DatasetOpsMixin: diff --git a/xarray/core/accessor_dt.py b/xarray/core/accessor_dt.py index 9669419a169..5c67af16d99 100644 --- a/xarray/core/accessor_dt.py +++ b/xarray/core/accessor_dt.py @@ -6,21 +6,21 @@ import numpy as np import pandas as pd -from ..coding.times import infer_calendar_name -from .common import ( +from xarray.coding.times import infer_calendar_name +from xarray.core.common import ( _contains_datetime_like_objects, is_np_datetime_like, is_np_timedelta_like, ) -from .pycompat import is_duck_dask_array -from .types import T_DataArray +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.types import T_DataArray if TYPE_CHECKING: from numpy.typing import DTypeLike - from .dataarray import DataArray - from .dataset import Dataset - from .types import CFCalendar + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import CFCalendar def _season_from_months(months): @@ -46,7 +46,7 @@ def _access_through_cftimeindex(values, name): """Coerce an array of datetime-like values to a CFTimeIndex and access requested datetime component """ - from ..coding.cftimeindex import CFTimeIndex + from xarray.coding.cftimeindex import CFTimeIndex values_as_cftimeindex = CFTimeIndex(values.ravel()) if name == "season": @@ -122,7 +122,7 @@ def _round_through_series_or_index(values, name, freq): """Coerce an array of datetime-like values to a pandas Series or xarray CFTimeIndex and apply requested rounding """ - from ..coding.cftimeindex import CFTimeIndex + from xarray.coding.cftimeindex import CFTimeIndex if is_np_datetime_like(values.dtype): values_as_series = pd.Series(values.ravel()) @@ -170,7 +170,7 @@ def _strftime_through_cftimeindex(values, date_format: str): """Coerce an array of cftime-like values to a CFTimeIndex and access requested datetime component """ - from ..coding.cftimeindex import CFTimeIndex + from xarray.coding.cftimeindex import CFTimeIndex values_as_cftimeindex = CFTimeIndex(values.ravel()) @@ -345,7 +345,7 @@ def isocalendar(self) -> Dataset: The iso year and weekday differ from the nominal year and weekday. """ - from .dataset import Dataset + from xarray.core.dataset import Dataset if not is_np_datetime_like(self._obj.data.dtype): raise AttributeError("'CFTimeIndex' object has no attribute 'isocalendar'") diff --git a/xarray/core/accessor_str.py b/xarray/core/accessor_str.py index 2c74d2bed1d..2e96abf9d47 100644 --- a/xarray/core/accessor_str.py +++ b/xarray/core/accessor_str.py @@ -49,13 +49,13 @@ import numpy as np -from .computation import apply_ufunc -from .types import T_DataArray +from xarray.core.computation import apply_ufunc +from xarray.core.types import T_DataArray if TYPE_CHECKING: from numpy.typing import DTypeLike - from .dataarray import DataArray + from xarray.core.dataarray import DataArray _cpython_optimized_encoders = ( "utf-8", diff --git a/xarray/core/alignment.py b/xarray/core/alignment.py index ef30d9afe85..1f00eecfdbe 100644 --- a/xarray/core/alignment.py +++ b/xarray/core/alignment.py @@ -22,9 +22,9 @@ import numpy as np import pandas as pd -from . import dtypes -from .common import DataWithCoords -from .indexes import ( +from xarray.core import dtypes +from xarray.core.common import DataWithCoords +from xarray.core.indexes import ( Index, Indexes, PandasIndex, @@ -32,13 +32,13 @@ indexes_all_equal, safe_cast_to_index, ) -from .utils import is_dict_like, is_full_slice -from .variable import Variable, as_compatible_data, calculate_dimensions +from xarray.core.utils import is_dict_like, is_full_slice +from xarray.core.variable import Variable, as_compatible_data, calculate_dimensions if TYPE_CHECKING: - from .dataarray import DataArray - from .dataset import Dataset - from .types import JoinOptions, T_DataArray, T_Dataset, T_DataWithCoords + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import JoinOptions, T_DataArray, T_Dataset, T_DataWithCoords DataAlignable = TypeVar("DataAlignable", bound=DataWithCoords) @@ -786,8 +786,8 @@ def deep_align( This function is not public API. """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset if indexes is None: indexes = {} @@ -942,8 +942,8 @@ def _broadcast_helper( arg: T_DataWithCoords, exclude, dims_map, common_coords ) -> T_DataWithCoords: - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset def _set_dims(var): # Add excluded dims to a copy of dims_map diff --git a/xarray/core/arithmetic.py b/xarray/core/arithmetic.py index 08c15019326..5b2cf38ee2e 100644 --- a/xarray/core/arithmetic.py +++ b/xarray/core/arithmetic.py @@ -6,17 +6,21 @@ import numpy as np # _typed_ops.py is a generated file -from ._typed_ops import ( +from xarray.core._typed_ops import ( DataArrayGroupByOpsMixin, DataArrayOpsMixin, DatasetGroupByOpsMixin, DatasetOpsMixin, VariableOpsMixin, ) -from .common import ImplementsArrayReduce, ImplementsDatasetReduce -from .ops import IncludeCumMethods, IncludeNumpySameMethods, IncludeReduceMethods -from .options import OPTIONS, _get_keep_attrs -from .pycompat import is_duck_array +from xarray.core.common import ImplementsArrayReduce, ImplementsDatasetReduce +from xarray.core.ops import ( + IncludeCumMethods, + IncludeNumpySameMethods, + IncludeReduceMethods, +) +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.pycompat import is_duck_array class SupportsArithmetic: @@ -40,7 +44,7 @@ class SupportsArithmetic: ) def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc # See the docstring example for numpy.lib.mixins.NDArrayOperatorsMixin. out = kwargs.get("out", ()) diff --git a/xarray/core/combine.py b/xarray/core/combine.py index f474d3beb19..d470dcb6192 100644 --- a/xarray/core/combine.py +++ b/xarray/core/combine.py @@ -7,15 +7,15 @@ import pandas as pd -from . import dtypes -from .concat import concat -from .dataarray import DataArray -from .dataset import Dataset -from .merge import merge -from .utils import iterate_nested +from xarray.core import dtypes +from xarray.core.concat import concat +from xarray.core.dataarray import DataArray +from xarray.core.dataset import Dataset +from xarray.core.merge import merge +from xarray.core.utils import iterate_nested if TYPE_CHECKING: - from .types import CombineAttrsOptions, CompatOptions, JoinOptions + from xarray.core.types import CombineAttrsOptions, CompatOptions, JoinOptions def _infer_concat_order_from_positions(datasets): diff --git a/xarray/core/common.py b/xarray/core/common.py index d1387d62e99..783847cd60d 100644 --- a/xarray/core/common.py +++ b/xarray/core/common.py @@ -20,10 +20,10 @@ import numpy as np import pandas as pd -from . import dtypes, duck_array_ops, formatting, formatting_html, ops -from .options import OPTIONS, _get_keep_attrs -from .pycompat import is_duck_dask_array -from .utils import Frozen, either_dict_or_kwargs, is_scalar +from xarray.core import dtypes, duck_array_ops, formatting, formatting_html, ops +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.utils import Frozen, either_dict_or_kwargs, is_scalar try: import cftime @@ -39,19 +39,19 @@ from numpy.typing import DTypeLike - from .dataarray import DataArray - from .dataset import Dataset - from .indexes import Index - from .resample import Resample - from .rolling_exp import RollingExp - from .types import ( + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.indexes import Index + from xarray.core.resample import Resample + from xarray.core.rolling_exp import RollingExp + from xarray.core.types import ( DatetimeLike, DTypeLikeSave, ScalarOrArray, SideOptions, T_DataWithCoords, ) - from .variable import Variable + from xarray.core.variable import Variable DTypeMaybeMapping = Union[DTypeLikeSave, Mapping[Any, DTypeLikeSave]] @@ -448,7 +448,7 @@ def clip( -------- numpy.clip : equivalent function """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc if keep_attrs is None: # When this was a unary func, the default was True, so retaining the @@ -803,7 +803,7 @@ def rolling_exp( -------- core.rolling_exp.RollingExp """ - from . import rolling_exp + from xarray.core import rolling_exp if "keep_attrs" in window_kwargs: warnings.warn( @@ -938,9 +938,9 @@ def _resample( """ # TODO support non-string indexer after removing the old API. - from ..coding.cftimeindex import CFTimeIndex - from .dataarray import DataArray - from .resample import RESAMPLE_DIM + from xarray.coding.cftimeindex import CFTimeIndex + from xarray.core.dataarray import DataArray + from xarray.core.resample import RESAMPLE_DIM if keep_attrs is not None: warnings.warn( @@ -978,7 +978,7 @@ def _resample( ) if isinstance(self._indexes[dim_name].to_pandas_index(), CFTimeIndex): - from .resample_cftime import CFTimeGrouper + from xarray.core.resample_cftime import CFTimeGrouper grouper = CFTimeGrouper( freq=freq, @@ -1095,9 +1095,9 @@ def where( numpy.where : corresponding numpy function where : equivalent function """ - from .alignment import align - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.alignment import align + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset if callable(cond): cond = cond(self) @@ -1188,7 +1188,7 @@ def isnull( array([False, True, False]) Dimensions without coordinates: x """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc if keep_attrs is None: keep_attrs = _get_keep_attrs(default=False) @@ -1233,7 +1233,7 @@ def notnull( array([ True, False, True]) Dimensions without coordinates: x """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc if keep_attrs is None: keep_attrs = _get_keep_attrs(default=False) @@ -1272,10 +1272,10 @@ def isin(self: T_DataWithCoords, test_elements: Any) -> T_DataWithCoords: -------- numpy.isin """ - from .computation import apply_ufunc - from .dataarray import DataArray - from .dataset import Dataset - from .variable import Variable + from xarray.core.computation import apply_ufunc + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.variable import Variable if isinstance(test_elements, Dataset): raise TypeError( @@ -1357,7 +1357,7 @@ def astype( dask.array.Array.astype sparse.COO.astype """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc kwargs = dict(order=order, casting=casting, subok=subok, copy=copy) kwargs = {k: v for k, v in kwargs.items() if v is not None} @@ -1527,9 +1527,9 @@ def full_like( ones_like """ - from .dataarray import DataArray - from .dataset import Dataset - from .variable import Variable + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.variable import Variable if not is_scalar(fill_value) and not ( isinstance(other, Dataset) and isinstance(fill_value, dict) @@ -1577,7 +1577,7 @@ def _full_like_variable( other: Variable, fill_value: Any, dtype: DTypeLike = None ) -> Variable: """Inner function of full_like, where other must be a variable""" - from .variable import Variable + from xarray.core.variable import Variable if fill_value is dtypes.NA: fill_value = dtypes.get_fill_value(dtype if dtype is not None else other.dtype) diff --git a/xarray/core/computation.py b/xarray/core/computation.py index 41d529b1093..c72f1d4a1ce 100644 --- a/xarray/core/computation.py +++ b/xarray/core/computation.py @@ -24,23 +24,23 @@ import numpy as np -from . import dtypes, duck_array_ops, utils -from .alignment import align, deep_align -from .common import zeros_like -from .duck_array_ops import datetime_to_numeric -from .indexes import Index, filter_indexes_from_coords -from .merge import merge_attrs, merge_coordinates_without_align -from .options import OPTIONS, _get_keep_attrs -from .pycompat import is_duck_dask_array -from .types import T_DataArray -from .utils import is_dict_like, is_scalar -from .variable import Variable +from xarray.core import dtypes, duck_array_ops, utils +from xarray.core.alignment import align, deep_align +from xarray.core.common import zeros_like +from xarray.core.duck_array_ops import datetime_to_numeric +from xarray.core.indexes import Index, filter_indexes_from_coords +from xarray.core.merge import merge_attrs, merge_coordinates_without_align +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.types import T_DataArray +from xarray.core.utils import is_dict_like, is_scalar +from xarray.core.variable import Variable if TYPE_CHECKING: - from .coordinates import Coordinates - from .dataarray import DataArray - from .dataset import Dataset - from .types import CombineAttrsOptions, JoinOptions + from xarray.core.coordinates import Coordinates + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import CombineAttrsOptions, JoinOptions _NO_FILL_VALUE = utils.ReprObject("") _DEFAULT_NAME = utils.ReprObject("") @@ -293,7 +293,7 @@ def apply_dataarray_vfunc( """Apply a variable level function over DataArray, Variable and/or ndarray objects. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if len(args) > 1: args = deep_align( @@ -436,7 +436,7 @@ def _fast_dataset( Beware: the `variables` dict is modified INPLACE. """ - from .dataset import Dataset + from xarray.core.dataset import Dataset variables.update(coord_variables) coord_names = set(coord_variables) @@ -456,7 +456,7 @@ def apply_dataset_vfunc( """Apply a variable level function over Dataset, dict of DataArray, DataArray, Variable and/or ndarray objects. """ - from .dataset import Dataset + from xarray.core.dataset import Dataset if dataset_join not in _JOINS_WITHOUT_FILL_VALUES and fill_value is _NO_FILL_VALUE: raise TypeError( @@ -504,7 +504,7 @@ def apply_dataset_vfunc( def _iter_over_selections(obj, dim, values): """Iterate over selections of an xarray object in the provided order.""" - from .groupby import _dummy_copy + from xarray.core.groupby import _dummy_copy dummy = None for value in values: @@ -521,8 +521,8 @@ def apply_groupby_func(func, *args): """Apply a dataset or datarray level function over GroupBy, Dataset, DataArray, Variable and/or ndarray objects. """ - from .groupby import GroupBy, peek_at - from .variable import Variable + from xarray.core.groupby import GroupBy, peek_at + from xarray.core.variable import Variable groupbys = [arg for arg in args if isinstance(arg, GroupBy)] assert groupbys, "must have at least one groupby to iterate over" @@ -670,7 +670,7 @@ def apply_variable_ufunc( dask_gufunc_kwargs=None, ) -> Variable | tuple[Variable, ...]: """Apply a ndarray level function over Variable and/or ndarray objects.""" - from .variable import Variable, as_compatible_data + from xarray.core.variable import Variable, as_compatible_data dim_sizes = unified_dim_sizes( (a for a in args if hasattr(a, "dims")), exclude_dims=exclude_dims @@ -1092,9 +1092,9 @@ def apply_ufunc( .. [1] https://numpy.org/doc/stable/reference/ufuncs.html .. [2] https://numpy.org/doc/stable/reference/c-api/generalized-ufuncs.html """ - from .dataarray import DataArray - from .groupby import GroupBy - from .variable import Variable + from xarray.core.dataarray import DataArray + from xarray.core.groupby import GroupBy + from xarray.core.variable import Variable if input_core_dims is None: input_core_dims = ((),) * (len(args)) @@ -1286,7 +1286,7 @@ def cov(da_a, da_b, dim=None, ddof=1): Coordinates: * space (space) array(235) """ - from .dataarray import DataArray - from .variable import Variable + from xarray.core.dataarray import DataArray + from xarray.core.variable import Variable if any(not isinstance(arr, (Variable, DataArray)) for arr in arrays): raise TypeError( @@ -1855,7 +1855,7 @@ def where(cond, x, y, keep_attrs=None): Dataset.where, DataArray.where : equivalent methods """ - from .dataset import Dataset + from xarray.core.dataset import Dataset if keep_attrs is None: keep_attrs = _get_keep_attrs(default=False) @@ -1995,7 +1995,7 @@ def _ensure_numeric(data: Dataset | DataArray) -> Dataset | DataArray: DataArray or Dataset Variables with datetime64 dtypes converted to float64. """ - from .dataset import Dataset + from xarray.core.dataset import Dataset def _cfoffset(x: DataArray) -> Any: scalar = x.compute().data[0] @@ -2126,7 +2126,7 @@ def unify_chunks(*objects: Dataset | DataArray) -> tuple[Dataset | DataArray, .. -------- dask.array.core.unify_chunks """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray # Convert all objects to datasets datasets = [ diff --git a/xarray/core/concat.py b/xarray/core/concat.py index 98eb0071da2..2eea2ecb3ee 100644 --- a/xarray/core/concat.py +++ b/xarray/core/concat.py @@ -4,22 +4,27 @@ import pandas as pd -from . import dtypes, utils -from .alignment import align -from .duck_array_ops import lazy_array_equiv -from .indexes import Index, PandasIndex -from .merge import ( +from xarray.core import dtypes, utils +from xarray.core.alignment import align +from xarray.core.duck_array_ops import lazy_array_equiv +from xarray.core.indexes import Index, PandasIndex +from xarray.core.merge import ( _VALID_COMPAT, collect_variables_and_indexes, merge_attrs, merge_collected, ) -from .types import T_DataArray, T_Dataset -from .variable import Variable -from .variable import concat as concat_vars +from xarray.core.types import T_DataArray, T_Dataset +from xarray.core.variable import Variable +from xarray.core.variable import concat as concat_vars if TYPE_CHECKING: - from .types import CombineAttrsOptions, CompatOptions, ConcatOptions, JoinOptions + from xarray.core.types import ( + CombineAttrsOptions, + CompatOptions, + ConcatOptions, + JoinOptions, + ) @overload @@ -214,8 +219,8 @@ def concat( # TODO: add ignore_index arguments copied from pandas.concat # TODO: support concatenating scalar coordinates even if the concatenated # dimension already exists - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset try: first_obj, objs = utils.peek_at(objs) @@ -265,7 +270,7 @@ def _calc_concat_dim_index( for concatenating along the new dimension. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray dim: Hashable | None @@ -441,8 +446,8 @@ def _dataset_concat( """ Concatenate a sequence of datasets along a new or existing dimension """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset datasets = list(datasets) @@ -628,7 +633,7 @@ def _dataarray_concat( join: JoinOptions = "outer", combine_attrs: CombineAttrsOptions = "override", ) -> T_DataArray: - from .dataarray import DataArray + from xarray.core.dataarray import DataArray arrays = list(arrays) diff --git a/xarray/core/coordinates.py b/xarray/core/coordinates.py index 3a6b70f117a..986b4cab443 100644 --- a/xarray/core/coordinates.py +++ b/xarray/core/coordinates.py @@ -7,17 +7,22 @@ import numpy as np import pandas as pd -from . import formatting -from .indexes import Index, Indexes, PandasMultiIndex, assert_no_index_corrupted -from .merge import merge_coordinates_without_align, merge_coords -from .utils import Frozen, ReprObject -from .variable import Variable, calculate_dimensions +from xarray.core import formatting +from xarray.core.indexes import ( + Index, + Indexes, + PandasMultiIndex, + assert_no_index_corrupted, +) +from xarray.core.merge import merge_coordinates_without_align, merge_coords +from xarray.core.utils import Frozen, ReprObject +from xarray.core.variable import Variable, calculate_dimensions if TYPE_CHECKING: - from .common import DataWithCoords - from .dataarray import DataArray - from .dataset import Dataset - from .types import T_DataArray + from xarray.core.common import DataWithCoords + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import T_DataArray # Used as the key corresponding to a DataArray's variable when converting # arbitrary DataArray objects to datasets @@ -222,7 +227,7 @@ def merge(self, other: Coordinates | None) -> Dataset: merged : Dataset A new Dataset with merged coordinates. """ - from .dataset import Dataset + from xarray.core.dataset import Dataset if other is None: return self.to_dataset() @@ -411,7 +416,7 @@ def variables(self): return Frozen(self._data._coords) def to_dataset(self) -> Dataset: - from .dataset import Dataset + from xarray.core.dataset import Dataset coords = {k: v.copy(deep=False) for k, v in self._data._coords.items()} indexes = dict(self._data.xindexes) diff --git a/xarray/core/dask_array_ops.py b/xarray/core/dask_array_ops.py index 8739067b083..d2d3e4a6d1c 100644 --- a/xarray/core/dask_array_ops.py +++ b/xarray/core/dask_array_ops.py @@ -1,6 +1,6 @@ from __future__ import annotations -from . import dtypes, nputils +from xarray.core import dtypes, nputils def dask_rolling_wrapper(moving_func, a, window, min_count=None, axis=-1): diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index f939a2c8b6e..273d1027283 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -20,39 +20,48 @@ import numpy as np import pandas as pd -from ..coding.calendar_ops import convert_calendar, interp_calendar -from ..coding.cftimeindex import CFTimeIndex -from ..plot.accessor import DataArrayPlotAccessor -from ..plot.utils import _get_units_from_attrs -from . import alignment, computation, dtypes, indexing, ops, utils -from ._aggregations import DataArrayAggregations -from .accessor_dt import CombinedDatetimelikeAccessor -from .accessor_str import StringAccessor -from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align -from .arithmetic import DataArrayArithmetic -from .common import AbstractArray, DataWithCoords, get_chunksizes -from .computation import unify_chunks -from .coordinates import DataArrayCoordinates, assert_coordinate_consistent -from .dataset import Dataset -from .formatting import format_item -from .indexes import ( +from xarray.coding.calendar_ops import convert_calendar, interp_calendar +from xarray.coding.cftimeindex import CFTimeIndex +from xarray.core import alignment, computation, dtypes, indexing, ops, utils +from xarray.core._aggregations import DataArrayAggregations +from xarray.core.accessor_dt import CombinedDatetimelikeAccessor +from xarray.core.accessor_str import StringAccessor +from xarray.core.alignment import ( + _broadcast_helper, + _get_broadcast_dims_map_common_coords, + align, +) +from xarray.core.arithmetic import DataArrayArithmetic +from xarray.core.common import AbstractArray, DataWithCoords, get_chunksizes +from xarray.core.computation import unify_chunks +from xarray.core.coordinates import DataArrayCoordinates, assert_coordinate_consistent +from xarray.core.dataset import Dataset +from xarray.core.formatting import format_item +from xarray.core.indexes import ( Index, Indexes, PandasMultiIndex, filter_indexes_from_coords, isel_indexes, ) -from .indexing import is_fancy_indexer, map_index_queries -from .merge import PANDAS_TYPES, MergeError, _create_indexes_from_coords -from .options import OPTIONS, _get_keep_attrs -from .utils import ( +from xarray.core.indexing import is_fancy_indexer, map_index_queries +from xarray.core.merge import PANDAS_TYPES, MergeError, _create_indexes_from_coords +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.utils import ( Default, HybridMappingProxy, ReprObject, _default, either_dict_or_kwargs, ) -from .variable import IndexVariable, Variable, as_compatible_data, as_variable +from xarray.core.variable import ( + IndexVariable, + Variable, + as_compatible_data, + as_variable, +) +from xarray.plot.accessor import DataArrayPlotAccessor +from xarray.plot.utils import _get_units_from_attrs if TYPE_CHECKING: from typing import TypeVar, Union @@ -72,11 +81,11 @@ except ImportError: iris_Cube = None - from ..backends.api import T_NetcdfEngine, T_NetcdfTypes - from .groupby import DataArrayGroupBy - from .resample import DataArrayResample - from .rolling import DataArrayCoarsen, DataArrayRolling - from .types import ( + from xarray.backends.api import T_NetcdfEngine, T_NetcdfTypes + from xarray.core.groupby import DataArrayGroupBy + from xarray.core.resample import DataArrayResample + from xarray.core.rolling import DataArrayCoarsen, DataArrayRolling + from xarray.core.types import ( CoarsenBoundaryOptions, DatetimeLike, DatetimeUnitOptions, @@ -94,7 +103,7 @@ T_DataArray, T_Xarray, ) - from .weighted import DataArrayWeighted + from xarray.core.weighted import DataArrayWeighted T_XarrayOther = TypeVar("T_XarrayOther", bound=Union["DataArray", Dataset]) @@ -801,7 +810,7 @@ def _item_key_to_dict(self, key: Any) -> Mapping[Hashable, Any]: return dict(zip(self.dims, key)) def _getitem_coord(self: T_DataArray, key: Any) -> T_DataArray: - from .dataset import _get_virtual_variable + from xarray.core.dataset import _get_virtual_variable try: var = self._coords[key] @@ -3408,7 +3417,7 @@ def interpolate_na( Coordinates: * x (x) int64 0 1 2 3 4 """ - from .missing import interp_na + from xarray.core.missing import interp_na return interp_na( self, @@ -3503,7 +3512,7 @@ def ffill( lon (X) float64 10.0 10.25 10.5 Dimensions without coordinates: Y, X """ - from .missing import ffill + from xarray.core.missing import ffill return ffill(self, dim, limit=limit) @@ -3589,7 +3598,7 @@ def bfill( lon (X) float64 10.0 10.25 10.5 Dimensions without coordinates: Y, X """ - from .missing import bfill + from xarray.core.missing import bfill return bfill(self, dim, limit=limit) @@ -3938,7 +3947,7 @@ def to_netcdf( -------- Dataset.to_netcdf """ - from ..backends.api import DATAARRAY_NAME, DATAARRAY_VARIABLE, to_netcdf + from xarray.backends.api import DATAARRAY_NAME, DATAARRAY_VARIABLE, to_netcdf if self.name is None: # If no name is set then use a generic xarray name @@ -4099,27 +4108,27 @@ def from_series(cls, series: pd.Series, sparse: bool = False) -> DataArray: def to_cdms2(self) -> cdms2_Variable: """Convert this array into a cdms2.Variable""" - from ..convert import to_cdms2 + from xarray.convert import to_cdms2 return to_cdms2(self) @classmethod def from_cdms2(cls, variable: cdms2_Variable) -> DataArray: """Convert a cdms2.Variable into an xarray.DataArray""" - from ..convert import from_cdms2 + from xarray.convert import from_cdms2 return from_cdms2(variable) def to_iris(self) -> iris_Cube: """Convert this array into a iris.cube.Cube""" - from ..convert import to_iris + from xarray.convert import to_iris return to_iris(self) @classmethod def from_iris(cls, cube: iris_Cube) -> DataArray: """Convert a iris.cube.Cube into an xarray.DataArray""" - from ..convert import from_iris + from xarray.convert import from_iris return from_iris(cube) @@ -4344,7 +4353,7 @@ def _binary_op( f: Callable, reflexive: bool = False, ) -> T_DataArray: - from .groupby import GroupBy + from xarray.core.groupby import GroupBy if isinstance(other, (Dataset, GroupBy)): return NotImplemented @@ -4365,7 +4374,7 @@ def _binary_op( return self._replace(variable, coords, name, indexes=indexes) def _inplace_binary_op(self: T_DataArray, other: Any, f: Callable) -> T_DataArray: - from .groupby import GroupBy + from xarray.core.groupby import GroupBy if isinstance(other, GroupBy): raise TypeError( @@ -5178,7 +5187,7 @@ def map_blocks( * time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00 month (time) int64 dask.array """ - from .parallel import map_blocks + from xarray.core.parallel import map_blocks return map_blocks(func, self, args, kwargs, template) @@ -6251,7 +6260,7 @@ def groupby( core.groupby.DataArrayGroupBy pandas.DataFrame.groupby """ - from .groupby import DataArrayGroupBy + from xarray.core.groupby import DataArrayGroupBy # While we don't generally check the type of every arg, passing # multiple dimensions as multiple arguments is common enough, and the @@ -6334,7 +6343,7 @@ def groupby_bins( ---------- .. [1] http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html """ - from .groupby import DataArrayGroupBy + from xarray.core.groupby import DataArrayGroupBy return DataArrayGroupBy( self, @@ -6374,7 +6383,7 @@ def weighted(self, weights: DataArray) -> DataArrayWeighted: -------- Dataset.weighted """ - from .weighted import DataArrayWeighted + from xarray.core.weighted import DataArrayWeighted return DataArrayWeighted(self, weights) @@ -6446,7 +6455,7 @@ def rolling( core.rolling.DataArrayRolling Dataset.rolling """ - from .rolling import DataArrayRolling + from xarray.core.rolling import DataArrayRolling dim = either_dict_or_kwargs(dim, window_kwargs, "rolling") return DataArrayRolling(self, dim, min_periods=min_periods, center=center) @@ -6515,7 +6524,7 @@ def coarsen( core.rolling.DataArrayCoarsen Dataset.coarsen """ - from .rolling import DataArrayCoarsen + from xarray.core.rolling import DataArrayCoarsen dim = either_dict_or_kwargs(dim, window_kwargs, "coarsen") return DataArrayCoarsen( @@ -6646,7 +6655,7 @@ def resample( ---------- .. [1] http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases """ - from .resample import DataArrayResample + from xarray.core.resample import DataArrayResample return self._resample( resample_cls=DataArrayResample, diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 4f376bdf811..2e2fd6efa72 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -33,20 +33,27 @@ import numpy as np import pandas as pd -from ..coding.calendar_ops import convert_calendar, interp_calendar -from ..coding.cftimeindex import CFTimeIndex, _parse_array_of_cftime_strings -from ..plot.accessor import DatasetPlotAccessor -from . import alignment -from . import dtypes as xrdtypes -from . import duck_array_ops, formatting, formatting_html, ops, utils -from ._aggregations import DatasetAggregations -from .alignment import _broadcast_helper, _get_broadcast_dims_map_common_coords, align -from .arithmetic import DatasetArithmetic -from .common import DataWithCoords, _contains_datetime_like_objects, get_chunksizes -from .computation import unify_chunks -from .coordinates import DatasetCoordinates, assert_coordinate_consistent -from .duck_array_ops import datetime_to_numeric -from .indexes import ( +from xarray.coding.calendar_ops import convert_calendar, interp_calendar +from xarray.coding.cftimeindex import CFTimeIndex, _parse_array_of_cftime_strings +from xarray.core import alignment +from xarray.core import dtypes as xrdtypes +from xarray.core import duck_array_ops, formatting, formatting_html, ops, utils +from xarray.core._aggregations import DatasetAggregations +from xarray.core.alignment import ( + _broadcast_helper, + _get_broadcast_dims_map_common_coords, + align, +) +from xarray.core.arithmetic import DatasetArithmetic +from xarray.core.common import ( + DataWithCoords, + _contains_datetime_like_objects, + get_chunksizes, +) +from xarray.core.computation import unify_chunks +from xarray.core.coordinates import DatasetCoordinates, assert_coordinate_consistent +from xarray.core.duck_array_ops import datetime_to_numeric +from xarray.core.indexes import ( Index, Indexes, PandasIndex, @@ -58,18 +65,18 @@ remove_unused_levels_categories, roll_indexes, ) -from .indexing import is_fancy_indexer, map_index_queries -from .merge import ( +from xarray.core.indexing import is_fancy_indexer, map_index_queries +from xarray.core.merge import ( dataset_merge_method, dataset_update_method, merge_coordinates_without_align, merge_data_and_coords, ) -from .missing import get_clean_interp_index -from .options import OPTIONS, _get_keep_attrs -from .pycompat import array_type, is_duck_dask_array -from .types import QuantileMethods, T_Dataset -from .utils import ( +from xarray.core.missing import get_clean_interp_index +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.pycompat import array_type, is_duck_dask_array +from xarray.core.types import QuantileMethods, T_Dataset +from xarray.core.utils import ( Default, Frozen, HybridMappingProxy, @@ -83,26 +90,27 @@ is_scalar, maybe_wrap_array, ) -from .variable import ( +from xarray.core.variable import ( IndexVariable, Variable, as_variable, broadcast_variables, calculate_dimensions, ) +from xarray.plot.accessor import DatasetPlotAccessor if TYPE_CHECKING: from numpy.typing import ArrayLike - from ..backends import AbstractDataStore, ZarrStore - from ..backends.api import T_NetcdfEngine, T_NetcdfTypes - from .coordinates import Coordinates - from .dataarray import DataArray - from .groupby import DatasetGroupBy - from .merge import CoercibleMapping - from .resample import DatasetResample - from .rolling import DatasetCoarsen, DatasetRolling - from .types import ( + from xarray.backends import AbstractDataStore, ZarrStore + from xarray.backends.api import T_NetcdfEngine, T_NetcdfTypes + from xarray.core.coordinates import Coordinates + from xarray.core.dataarray import DataArray + from xarray.core.groupby import DatasetGroupBy + from xarray.core.merge import CoercibleMapping + from xarray.core.resample import DatasetResample + from xarray.core.rolling import DatasetCoarsen, DatasetRolling + from xarray.core.types import ( CFCalendar, CoarsenBoundaryOptions, CombineAttrsOptions, @@ -122,7 +130,7 @@ SideOptions, T_Xarray, ) - from .weighted import DatasetWeighted + from xarray.core.weighted import DatasetWeighted try: from dask.delayed import Delayed @@ -160,7 +168,7 @@ def _get_virtual_variable( objects (if possible) """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if dim_sizes is None: dim_sizes = {} @@ -1334,7 +1342,7 @@ def _copy_listed(self: T_Dataset, names: Iterable[Hashable]) -> T_Dataset: def _construct_dataarray(self, name: Hashable) -> DataArray: """Construct a DataArray by indexing this dataset""" - from .dataarray import DataArray + from xarray.core.dataarray import DataArray try: variable = self._variables[name] @@ -1454,7 +1462,7 @@ def __setitem__( ``(dims, data[, attrs])``), add it to this dataset as a new variable. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if utils.is_dict_like(key): # check for consistency and convert value to dataset @@ -1512,8 +1520,8 @@ def _setitem_check(self, key, value): When assigning values to a subset of a Dataset, do consistency check beforehand to avoid leaving the dataset in a partially updated state when an error occurs. """ - from .alignment import align - from .dataarray import DataArray + from xarray.core.alignment import align + from xarray.core.dataarray import DataArray if isinstance(value, Dataset): missing_vars = [ @@ -1753,7 +1761,7 @@ def reset_coords( def dump_to_store(self, store: AbstractDataStore, **kwargs) -> None: """Store dataset contents to a backends.*DataStore object.""" - from ..backends.api import dump_to_store + from xarray.backends.api import dump_to_store # TODO: rename and/or cleanup this method to make it more consistent # with to_netcdf() @@ -1899,7 +1907,7 @@ def to_netcdf( """ if encoding is None: encoding = {} - from ..backends.api import to_netcdf + from xarray.backends.api import to_netcdf return to_netcdf( # type: ignore # mypy cannot resolve the overloads:( self, @@ -2086,7 +2094,7 @@ def to_zarr( :ref:`io.zarr` The I/O user guide, with more details and examples. """ - from ..backends.api import to_zarr + from xarray.backends.api import to_zarr return to_zarr( # type: ignore self, @@ -2267,8 +2275,8 @@ def _validate_indexers( + string indexers are cast to the appropriate date type if the associated index is a DatetimeIndex or CFTimeIndex """ - from ..coding.cftimeindex import CFTimeIndex - from .dataarray import DataArray + from xarray.coding.cftimeindex import CFTimeIndex + from xarray.core.dataarray import DataArray indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims) @@ -2329,7 +2337,7 @@ def _get_indexers_coords_and_indexes(self, indexers): Only coordinate with a name different from any of self.variables will be attached. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray coords_list = [] for k, v in indexers.items(): @@ -3296,7 +3304,7 @@ def interp( a (x) float64 5.0 6.5 6.25 4.75 b (x, y) float64 2.5 3.0 nan 4.0 5.625 nan nan nan nan nan nan nan """ - from . import missing + from xarray.core import missing if kwargs is None: kwargs = {} @@ -4667,7 +4675,7 @@ def to_stacked_array( Dimensions without coordinates: x """ - from .concat import concat + from xarray.core.concat import concat stacking_dims = tuple(dim for dim in self.dims if dim not in sample_dims) @@ -5023,7 +5031,7 @@ def merge( -------- Dataset.update """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray other = other.to_dataset() if isinstance(other, DataArray) else other merge_result = dataset_merge_method( @@ -5710,7 +5718,7 @@ def interpolate_na( C (x) float64 20.0 15.0 10.0 5.0 0.0 D (x) float64 5.0 3.0 1.0 -1.0 4.0 """ - from .missing import _apply_over_vars_with_dim, interp_na + from xarray.core.missing import _apply_over_vars_with_dim, interp_na new = _apply_over_vars_with_dim( interp_na, @@ -5745,7 +5753,7 @@ def ffill(self: T_Dataset, dim: Hashable, limit: int | None = None) -> T_Dataset ------- Dataset """ - from .missing import _apply_over_vars_with_dim, ffill + from xarray.core.missing import _apply_over_vars_with_dim, ffill new = _apply_over_vars_with_dim(ffill, self, dim=dim, limit=limit) return new @@ -5771,7 +5779,7 @@ def bfill(self: T_Dataset, dim: Hashable, limit: int | None = None) -> T_Dataset ------- Dataset """ - from .missing import _apply_over_vars_with_dim, bfill + from xarray.core.missing import _apply_over_vars_with_dim, bfill new = _apply_over_vars_with_dim(bfill, self, dim=dim, limit=limit) return new @@ -6092,7 +6100,7 @@ def to_array( ------- array : xarray.DataArray """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray data_vars = [self.variables[k] for k in self.data_vars] broadcast_vars = broadcast_variables(*data_vars) @@ -6574,8 +6582,8 @@ def _unary_op(self: T_Dataset, f, *args, **kwargs) -> T_Dataset: return self._replace_with_new_dims(variables, attrs=attrs) def _binary_op(self, other, f, reflexive=False, join=None) -> Dataset: - from .dataarray import DataArray - from .groupby import GroupBy + from xarray.core.dataarray import DataArray + from xarray.core.groupby import GroupBy if isinstance(other, GroupBy): return NotImplemented @@ -6587,8 +6595,8 @@ def _binary_op(self, other, f, reflexive=False, join=None) -> Dataset: return ds def _inplace_binary_op(self: T_Dataset, other, f) -> T_Dataset: - from .dataarray import DataArray - from .groupby import GroupBy + from xarray.core.dataarray import DataArray + from xarray.core.groupby import GroupBy if isinstance(other, GroupBy): raise TypeError( @@ -6964,7 +6972,7 @@ def sortby( A (x, y) int64 3 4 1 2 B (x, y) int64 7 8 5 6 """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if not isinstance(variables, list): variables = [variables] @@ -7253,7 +7261,7 @@ def differentiate( -------- numpy.gradient: corresponding numpy function """ - from .variable import Variable + from xarray.core.variable import Variable if coord not in self.variables and coord not in self.dims: raise ValueError(f"Coordinate {coord} does not exist.") @@ -7355,7 +7363,7 @@ def integrate( return result def _integrate_one(self, coord, datetime_unit=None, cumulative=False): - from .variable import Variable + from xarray.core.variable import Variable if coord not in self.variables and coord not in self.dims: raise ValueError(f"Coordinate {coord} does not exist.") @@ -7718,7 +7726,7 @@ def map_blocks( Data variables: a (time) float64 dask.array """ - from .parallel import map_blocks + from xarray.core.parallel import map_blocks return map_blocks(func, self, args, kwargs, template) @@ -7790,7 +7798,7 @@ def polyfit( numpy.polyval xarray.polyval """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray variables = {} skipna_da = skipna @@ -8571,9 +8579,9 @@ def curvefit( """ from scipy.optimize import curve_fit - from .alignment import broadcast - from .computation import apply_ufunc - from .dataarray import _THIS_ARRAY, DataArray + from xarray.core.alignment import broadcast + from xarray.core.computation import apply_ufunc + from xarray.core.dataarray import _THIS_ARRAY, DataArray if p0 is None: p0 = {} @@ -8913,7 +8921,7 @@ def groupby( core.groupby.DatasetGroupBy pandas.DataFrame.groupby """ - from .groupby import DatasetGroupBy + from xarray.core.groupby import DatasetGroupBy # While we don't generally check the type of every arg, passing # multiple dimensions as multiple arguments is common enough, and the @@ -8996,7 +9004,7 @@ def groupby_bins( ---------- .. [1] http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html """ - from .groupby import DatasetGroupBy + from xarray.core.groupby import DatasetGroupBy return DatasetGroupBy( self, @@ -9036,7 +9044,7 @@ def weighted(self, weights: DataArray) -> DatasetWeighted: -------- DataArray.weighted """ - from .weighted import DatasetWeighted + from xarray.core.weighted import DatasetWeighted return DatasetWeighted(self, weights) @@ -9074,7 +9082,7 @@ def rolling( core.rolling.DatasetRolling DataArray.rolling """ - from .rolling import DatasetRolling + from xarray.core.rolling import DatasetRolling dim = either_dict_or_kwargs(dim, window_kwargs, "rolling") return DatasetRolling(self, dim, min_periods=min_periods, center=center) @@ -9112,7 +9120,7 @@ def coarsen( core.rolling.DatasetCoarsen DataArray.coarsen """ - from .rolling import DatasetCoarsen + from xarray.core.rolling import DatasetCoarsen dim = either_dict_or_kwargs(dim, window_kwargs, "coarsen") return DatasetCoarsen( @@ -9196,7 +9204,7 @@ def resample( ---------- .. [1] http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases """ - from .resample import DatasetResample + from xarray.core.resample import DatasetResample return self._resample( resample_cls=DatasetResample, diff --git a/xarray/core/dtypes.py b/xarray/core/dtypes.py index d5371e9629a..4d8583cfe65 100644 --- a/xarray/core/dtypes.py +++ b/xarray/core/dtypes.py @@ -4,7 +4,7 @@ import numpy as np -from . import utils +from xarray.core import utils # Use as a sentinel value to indicate a dtype appropriate NA value. NA = utils.ReprObject("") diff --git a/xarray/core/duck_array_ops.py b/xarray/core/duck_array_ops.py index 29ab44bb8ba..6aba6617c37 100644 --- a/xarray/core/duck_array_ops.py +++ b/xarray/core/duck_array_ops.py @@ -32,10 +32,10 @@ ) from numpy.lib.stride_tricks import sliding_window_view # noqa -from . import dask_array_ops, dtypes, nputils -from .nputils import nanfirst, nanlast -from .pycompat import array_type, is_duck_dask_array -from .utils import is_duck_array, module_available +from xarray.core import dask_array_ops, dtypes, nputils +from xarray.core.nputils import nanfirst, nanlast +from xarray.core.pycompat import array_type, is_duck_dask_array +from xarray.core.utils import is_duck_array, module_available dask_available = module_available("dask") @@ -336,7 +336,7 @@ def _ignore_warnings_if(condition): def _create_nan_agg_method(name, coerce_strings=False, invariant_0d=False): - from . import nanops + from xarray.core import nanops def f(values, axis=None, skipna=None, **kwargs): if kwargs.pop("out", None) is not None: @@ -581,7 +581,7 @@ def py_timedelta_to_float(array, datetime_unit): def mean(array, axis=None, skipna=None, **kwargs): """inhouse mean that can handle np.datetime64 or cftime.datetime dtypes""" - from .common import _contains_cftime_datetimes + from xarray.core.common import _contains_cftime_datetimes array = asarray(array) if array.dtype.kind in "Mm": diff --git a/xarray/core/extensions.py b/xarray/core/extensions.py index d40151e48fb..efe00718a79 100644 --- a/xarray/core/extensions.py +++ b/xarray/core/extensions.py @@ -2,8 +2,8 @@ import warnings -from .dataarray import DataArray -from .dataset import Dataset +from xarray.core.dataarray import DataArray +from xarray.core.dataset import Dataset class AccessorRegistrationWarning(Warning): diff --git a/xarray/core/formatting.py b/xarray/core/formatting.py index 351a4b27687..1473d513a01 100644 --- a/xarray/core/formatting.py +++ b/xarray/core/formatting.py @@ -15,11 +15,11 @@ import pandas as pd from pandas.errors import OutOfBoundsDatetime -from .duck_array_ops import array_equiv -from .indexing import MemoryCachedArray -from .options import OPTIONS, _get_boolean_with_default -from .pycompat import array_type -from .utils import is_duck_array +from xarray.core.duck_array_ops import array_equiv +from xarray.core.indexing import MemoryCachedArray +from xarray.core.options import OPTIONS, _get_boolean_with_default +from xarray.core.pycompat import array_type +from xarray.core.utils import is_duck_array def pretty_print(x, numchars: int): @@ -437,7 +437,7 @@ def summarize_index( def nondefault_indexes(indexes): - from .indexes import PandasIndex, PandasMultiIndex + from xarray.core.indexes import PandasIndex, PandasMultiIndex default_indexes = (PandasIndex, PandasMultiIndex) @@ -594,7 +594,7 @@ def short_data_repr(array): @recursive_repr("") def array_repr(arr): - from .variable import Variable + from xarray.core.variable import Variable max_rows = OPTIONS["display_max_rows"] diff --git a/xarray/core/formatting_html.py b/xarray/core/formatting_html.py index ee1805f6d2b..d8d20a9e2c0 100644 --- a/xarray/core/formatting_html.py +++ b/xarray/core/formatting_html.py @@ -6,8 +6,12 @@ from html import escape from importlib.resources import read_binary -from .formatting import inline_index_repr, inline_variable_array_repr, short_data_repr -from .options import _get_boolean_with_default +from xarray.core.formatting import ( + inline_index_repr, + inline_variable_array_repr, + short_data_repr, +) +from xarray.core.options import _get_boolean_with_default STATIC_FILES = ( ("xarray.static.html", "icons-svg-inline.html"), diff --git a/xarray/core/groupby.py b/xarray/core/groupby.py index 589f6c98c2a..a6516611efc 100644 --- a/xarray/core/groupby.py +++ b/xarray/core/groupby.py @@ -20,30 +20,39 @@ import numpy as np import pandas as pd -from . import dtypes, duck_array_ops, nputils, ops -from ._aggregations import DataArrayGroupByAggregations, DatasetGroupByAggregations -from .alignment import align -from .arithmetic import DataArrayGroupbyArithmetic, DatasetGroupbyArithmetic -from .common import ImplementsArrayReduce, ImplementsDatasetReduce -from .concat import concat -from .formatting import format_array_flat -from .indexes import ( +from xarray.core import dtypes, duck_array_ops, nputils, ops +from xarray.core._aggregations import ( + DataArrayGroupByAggregations, + DatasetGroupByAggregations, +) +from xarray.core.alignment import align +from xarray.core.arithmetic import DataArrayGroupbyArithmetic, DatasetGroupbyArithmetic +from xarray.core.common import ImplementsArrayReduce, ImplementsDatasetReduce +from xarray.core.concat import concat +from xarray.core.formatting import format_array_flat +from xarray.core.indexes import ( create_default_index_implicit, filter_indexes_from_coords, safe_cast_to_index, ) -from .options import _get_keep_attrs -from .pycompat import integer_types -from .types import Dims, QuantileMethods, T_Xarray -from .utils import either_dict_or_kwargs, hashable, is_scalar, maybe_wrap_array, peek_at -from .variable import IndexVariable, Variable +from xarray.core.options import _get_keep_attrs +from xarray.core.pycompat import integer_types +from xarray.core.types import Dims, QuantileMethods, T_Xarray +from xarray.core.utils import ( + either_dict_or_kwargs, + hashable, + is_scalar, + maybe_wrap_array, + peek_at, +) +from xarray.core.variable import IndexVariable, Variable if TYPE_CHECKING: from numpy.typing import ArrayLike - from .dataarray import DataArray - from .dataset import Dataset - from .utils import Frozen + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.utils import Frozen GroupKey = Any @@ -92,8 +101,8 @@ def unique_value_groups( def _dummy_copy(xarray_obj): - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset if isinstance(xarray_obj, Dataset): res = Dataset( @@ -220,7 +229,7 @@ def _ensure_1d( group: T_Group, obj: T_Xarray ) -> tuple[T_Group, T_Xarray, Hashable | None, list[Hashable]]: # 1D cases: do nothing - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if isinstance(group, (IndexVariable, _DummyGroup)) or group.ndim == 1: return group, obj, None, [] @@ -349,7 +358,7 @@ def __init__( """ if cut_kwargs is None: cut_kwargs = {} - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if grouper is not None and bins is not None: raise TypeError("can't specify both `grouper` and `bins`") @@ -534,7 +543,7 @@ def __repr__(self) -> str: ) def _get_index_and_items(self, index, grouper): - from .resample_cftime import CFTimeGrouper + from xarray.core.resample_cftime import CFTimeGrouper s = pd.Series(np.arange(index.size), index) if isinstance(grouper, CFTimeGrouper): @@ -566,8 +575,8 @@ def _infer_concat_args(self, applied_example): return coord, dim, positions def _binary_op(self, other, f, reflexive=False): - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset g = f if not reflexive else lambda x, y: f(y, x) @@ -659,7 +668,7 @@ def _flox_reduce( """Adaptor function that translates our groupby API to that of flox.""" from flox.xarray import xarray_reduce - from .dataset import Dataset + from xarray.core.dataset import Dataset obj = self._original_obj diff --git a/xarray/core/indexes.py b/xarray/core/indexes.py index a768155ba7d..f3f03c9495b 100644 --- a/xarray/core/indexes.py +++ b/xarray/core/indexes.py @@ -20,13 +20,17 @@ import numpy as np import pandas as pd -from . import formatting, nputils, utils -from .indexing import IndexSelResult, PandasIndexingAdapter, PandasMultiIndexingAdapter -from .utils import Frozen, get_valid_numpy_dtype, is_dict_like, is_scalar +from xarray.core import formatting, nputils, utils +from xarray.core.indexing import ( + IndexSelResult, + PandasIndexingAdapter, + PandasMultiIndexingAdapter, +) +from xarray.core.utils import Frozen, get_valid_numpy_dtype, is_dict_like, is_scalar if TYPE_CHECKING: - from .types import ErrorOptions, T_Index - from .variable import Variable + from xarray.core.types import ErrorOptions, T_Index + from xarray.core.variable import Variable IndexVars = Dict[Any, "Variable"] @@ -140,7 +144,7 @@ def _repr_inline_(self, max_width): def _maybe_cast_to_cftimeindex(index: pd.Index) -> pd.Index: - from ..coding.cftimeindex import CFTimeIndex + from xarray.coding.cftimeindex import CFTimeIndex if len(index) > 0 and index.dtype == "O": try: @@ -160,8 +164,8 @@ def safe_cast_to_index(array: Any) -> pd.Index: this function will not attempt to do automatic type conversion but will always return an index with dtype=object. """ - from .dataarray import DataArray - from .variable import Variable + from xarray.core.dataarray import DataArray + from xarray.core.variable import Variable if isinstance(array, pd.Index): index = array @@ -182,8 +186,8 @@ def safe_cast_to_index(array: Any) -> pd.Index: def _sanitize_slice_element(x): - from .dataarray import DataArray - from .variable import Variable + from xarray.core.dataarray import DataArray + from xarray.core.variable import Variable if not isinstance(x, tuple) and len(np.shape(x)) != 0: raise ValueError( @@ -387,7 +391,7 @@ def concat( def create_variables( self, variables: Mapping[Any, Variable] | None = None ) -> IndexVars: - from .variable import IndexVariable + from xarray.core.variable import IndexVariable name = self.index.name attrs: Mapping[Hashable, Any] | None @@ -411,7 +415,7 @@ def to_pandas_index(self) -> pd.Index: def isel( self, indexers: Mapping[Any, int | slice | np.ndarray | Variable] ) -> PandasIndex | None: - from .variable import Variable + from xarray.core.variable import Variable indxr = indexers[self.dim] if isinstance(indxr, Variable): @@ -429,8 +433,8 @@ def isel( def sel( self, labels: dict[Any, Any], method=None, tolerance=None ) -> IndexSelResult: - from .dataarray import DataArray - from .variable import Variable + from xarray.core.dataarray import DataArray + from xarray.core.variable import Variable if method is not None and not isinstance(method, str): raise TypeError("``method`` must be a string") @@ -814,7 +818,7 @@ def reorder_levels( def create_variables( self, variables: Mapping[Any, Variable] | None = None ) -> IndexVars: - from .variable import IndexVariable + from xarray.core.variable import IndexVariable if variables is None: variables = {} @@ -848,8 +852,8 @@ def create_variables( return index_vars def sel(self, labels, method=None, tolerance=None) -> IndexSelResult: - from .dataarray import DataArray - from .variable import Variable + from xarray.core.dataarray import DataArray + from xarray.core.variable import Variable if method is not None or tolerance is not None: raise ValueError( @@ -1157,7 +1161,7 @@ def variables(self) -> Mapping[Hashable, Variable]: @property def dims(self) -> Mapping[Hashable, int]: - from .variable import calculate_dimensions + from xarray.core.variable import calculate_dimensions if self._dims is None: self._dims = calculate_dimensions(self._variables) @@ -1237,7 +1241,7 @@ def get_all_dims( A dictionary of all dimensions shared by an index. """ - from .variable import calculate_dimensions + from xarray.core.variable import calculate_dimensions return calculate_dimensions(self.get_all_coords(key, errors=errors)) diff --git a/xarray/core/indexing.py b/xarray/core/indexing.py index 8dd2d1a0ead..ba937183d24 100644 --- a/xarray/core/indexing.py +++ b/xarray/core/indexing.py @@ -14,12 +14,17 @@ import pandas as pd from packaging.version import Version -from . import duck_array_ops -from .nputils import NumpyVIndexAdapter -from .options import OPTIONS -from .pycompat import array_type, integer_types, is_duck_dask_array, mod_version -from .types import T_Xarray -from .utils import ( +from xarray.core import duck_array_ops +from xarray.core.nputils import NumpyVIndexAdapter +from xarray.core.options import OPTIONS +from xarray.core.pycompat import ( + array_type, + integer_types, + is_duck_dask_array, + mod_version, +) +from xarray.core.types import T_Xarray +from xarray.core.utils import ( NDArrayMixin, either_dict_or_kwargs, get_valid_numpy_dtype, @@ -29,8 +34,8 @@ if TYPE_CHECKING: from numpy.typing import DTypeLike - from .indexes import Index - from .variable import Variable + from xarray.core.indexes import Index + from xarray.core.variable import Variable @dataclass @@ -163,7 +168,7 @@ def map_index_queries( and return the (merged) query results. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray # TODO benbovy - flexible indexes: remove when custom index options are available if method is None and tolerance is None: @@ -1415,7 +1420,7 @@ class PandasIndexingAdapter(ExplicitlyIndexedNDArrayMixin): __slots__ = ("array", "_dtype") def __init__(self, array: pd.Index, dtype: DTypeLike = None): - from .indexes import safe_cast_to_index + from xarray.core.indexes import safe_cast_to_index self.array = safe_cast_to_index(array) @@ -1566,7 +1571,7 @@ def _get_array_subset(self) -> np.ndarray: return np.asarray(subset) def _repr_inline_(self, max_width: int) -> str: - from .formatting import format_array_flat + from xarray.core.formatting import format_array_flat if self.level is None: return "MultiIndex" @@ -1574,7 +1579,7 @@ def _repr_inline_(self, max_width: int) -> str: return format_array_flat(self._get_array_subset(), max_width) def _repr_html_(self) -> str: - from .formatting import short_numpy_repr + from xarray.core.formatting import short_numpy_repr array_repr = short_numpy_repr(self._get_array_subset()) return f"
{escape(array_repr)}
" diff --git a/xarray/core/merge.py b/xarray/core/merge.py index 8a8fc6f1074..77cfb9bed75 100644 --- a/xarray/core/merge.py +++ b/xarray/core/merge.py @@ -17,24 +17,24 @@ import pandas as pd -from . import dtypes -from .alignment import deep_align -from .duck_array_ops import lazy_array_equiv -from .indexes import ( +from xarray.core import dtypes +from xarray.core.alignment import deep_align +from xarray.core.duck_array_ops import lazy_array_equiv +from xarray.core.indexes import ( Index, Indexes, create_default_index_implicit, filter_indexes_from_coords, indexes_equal, ) -from .utils import Frozen, compat_dict_union, dict_equiv, equivalent -from .variable import Variable, as_variable, calculate_dimensions +from xarray.core.utils import Frozen, compat_dict_union, dict_equiv, equivalent +from xarray.core.variable import Variable, as_variable, calculate_dimensions if TYPE_CHECKING: - from .coordinates import Coordinates - from .dataarray import DataArray - from .dataset import Dataset - from .types import CombineAttrsOptions, CompatOptions, JoinOptions + from xarray.core.coordinates import Coordinates + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import CombineAttrsOptions, CompatOptions, JoinOptions DimsLike = Union[Hashable, Sequence[Hashable]] ArrayLike = Any @@ -333,8 +333,8 @@ def collect_variables_and_indexes( with a matching key/name. """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset if indexes is None: indexes = {} @@ -442,8 +442,8 @@ def determine_coords( All variable found in the input should appear in either the set of coordinate or non-coordinate names. """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset coord_names: set[Hashable] = set() noncoord_names: set[Hashable] = set() @@ -477,8 +477,8 @@ def coerce_pandas_values(objects: Iterable[CoercibleMapping]) -> list[DatasetLik List of Dataset or dictionary objects. Any inputs or values in the inputs that were pandas objects have been converted into native xarray objects. """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset out = [] for obj in objects: @@ -743,8 +743,8 @@ def merge_core( ------ MergeError if the merge cannot be done successfully. """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset _assert_compat_valid(compat) @@ -1008,8 +1008,8 @@ def merge( combine_nested combine_by_coords """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset dict_like_objects = [] for obj in objects: @@ -1085,8 +1085,8 @@ def dataset_update_method(dataset: Dataset, other: CoercibleMapping) -> _MergeRe `xarray.Dataset`, e.g., if it's a dict with DataArray values (GH2068, GH2180). """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset if not isinstance(other, Dataset): other = dict(other) diff --git a/xarray/core/missing.py b/xarray/core/missing.py index 93423a4beff..3676db9a487 100644 --- a/xarray/core/missing.py +++ b/xarray/core/missing.py @@ -10,19 +10,19 @@ import pandas as pd from packaging.version import Version -from . import utils -from .common import _contains_datetime_like_objects, ones_like -from .computation import apply_ufunc -from .duck_array_ops import datetime_to_numeric, push, timedelta_to_numeric -from .options import OPTIONS, _get_keep_attrs -from .pycompat import is_duck_dask_array, mod_version -from .types import Interp1dOptions, InterpOptions -from .utils import OrderedSet, is_scalar -from .variable import Variable, broadcast_variables +from xarray.core import utils +from xarray.core.common import _contains_datetime_like_objects, ones_like +from xarray.core.computation import apply_ufunc +from xarray.core.duck_array_ops import datetime_to_numeric, push, timedelta_to_numeric +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.pycompat import is_duck_dask_array, mod_version +from xarray.core.types import Interp1dOptions, InterpOptions +from xarray.core.utils import OrderedSet, is_scalar +from xarray.core.variable import Variable, broadcast_variables if TYPE_CHECKING: - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset def _get_nan_block_lengths( diff --git a/xarray/core/nanops.py b/xarray/core/nanops.py index 651fd9aca17..022de845c4c 100644 --- a/xarray/core/nanops.py +++ b/xarray/core/nanops.py @@ -4,8 +4,15 @@ import numpy as np -from . import dtypes, nputils, utils -from .duck_array_ops import count, fillna, isnull, sum_where, where, where_method +from xarray.core import dtypes, nputils, utils +from xarray.core.duck_array_ops import ( + count, + fillna, + isnull, + sum_where, + where, + where_method, +) def _maybe_null_out(result, axis, mask, min_count=1): @@ -93,7 +100,7 @@ def nansum(a, axis=None, dtype=None, out=None, min_count=None): def _nanmean_ddof_object(ddof, value, axis=None, dtype=None, **kwargs): """In house nanmean. ddof argument will be used in _nanvar method""" - from .duck_array_ops import count, fillna, where_method + from xarray.core.duck_array_ops import count, fillna, where_method valid_count = count(value, axis=axis) value = fillna(value, 0) diff --git a/xarray/core/nputils.py b/xarray/core/nputils.py index d1131168c1f..80c988ebd4f 100644 --- a/xarray/core/nputils.py +++ b/xarray/core/nputils.py @@ -6,7 +6,7 @@ import pandas as pd from numpy.core.multiarray import normalize_axis_index # type: ignore[attr-defined] -from .options import OPTIONS +from xarray.core.options import OPTIONS try: import bottleneck as bn diff --git a/xarray/core/ops.py b/xarray/core/ops.py index 07b5a0b56fe..009616c5f12 100644 --- a/xarray/core/ops.py +++ b/xarray/core/ops.py @@ -10,7 +10,7 @@ import numpy as np -from . import dtypes, duck_array_ops +from xarray.core import dtypes, duck_array_ops try: import bottleneck as bn @@ -141,7 +141,7 @@ def fillna(data, other, join="left", dataset_join="left"): - "left": take only variables from the first object - "right": take only variables from the last object """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc return apply_ufunc( duck_array_ops.fillna, @@ -170,7 +170,7 @@ def where_method(self, cond, other=dtypes.NA): ------- Same type as caller. """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc # alignment for three arguments is complicated, so don't support it yet join = "inner" if other is dtypes.NA else "exact" diff --git a/xarray/core/options.py b/xarray/core/options.py index f7f5b9eddcd..eb0c56c7ee0 100644 --- a/xarray/core/options.py +++ b/xarray/core/options.py @@ -3,7 +3,7 @@ import warnings from typing import TYPE_CHECKING, Literal, TypedDict -from .utils import FrozenDict +from xarray.core.utils import FrozenDict if TYPE_CHECKING: try: @@ -106,7 +106,7 @@ def _positive_integer(value: int) -> bool: def _set_file_cache_maxsize(value) -> None: - from ..backends.file_manager import FILE_CACHE + from xarray.backends.file_manager import FILE_CACHE FILE_CACHE.maxsize = value diff --git a/xarray/core/parallel.py b/xarray/core/parallel.py index 0ef428e3d96..92d1f777705 100644 --- a/xarray/core/parallel.py +++ b/xarray/core/parallel.py @@ -16,13 +16,13 @@ import numpy as np -from .alignment import align -from .dataarray import DataArray -from .dataset import Dataset -from .pycompat import is_dask_collection +from xarray.core.alignment import align +from xarray.core.dataarray import DataArray +from xarray.core.dataset import Dataset +from xarray.core.pycompat import is_dask_collection if TYPE_CHECKING: - from .types import T_Xarray + from xarray.core.types import T_Xarray def unzip(iterable): diff --git a/xarray/core/pycompat.py b/xarray/core/pycompat.py index 474b694dcf0..fa788821b4f 100644 --- a/xarray/core/pycompat.py +++ b/xarray/core/pycompat.py @@ -7,7 +7,7 @@ import numpy as np from packaging.version import Version -from .utils import is_duck_array, module_available +from xarray.core.utils import is_duck_array, module_available integer_types = (int, np.integer) diff --git a/xarray/core/resample.py b/xarray/core/resample.py index 61a12f1b446..8b66aac5042 100644 --- a/xarray/core/resample.py +++ b/xarray/core/resample.py @@ -5,13 +5,16 @@ import numpy as np -from ._aggregations import DataArrayResampleAggregations, DatasetResampleAggregations -from .groupby import DataArrayGroupByBase, DatasetGroupByBase, GroupBy -from .types import Dims, InterpOptions, T_Xarray +from xarray.core._aggregations import ( + DataArrayResampleAggregations, + DatasetResampleAggregations, +) +from xarray.core.groupby import DataArrayGroupByBase, DatasetGroupByBase, GroupBy +from xarray.core.types import Dims, InterpOptions, T_Xarray if TYPE_CHECKING: - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset RESAMPLE_DIM = "__resample_dim__" @@ -54,7 +57,7 @@ def _flox_reduce( **kwargs, ) -> T_Xarray: - from .dataarray import DataArray + from xarray.core.dataarray import DataArray kwargs.setdefault("method", "cohorts") diff --git a/xarray/core/resample_cftime.py b/xarray/core/resample_cftime.py index da21fdd17cf..7fdd372ec74 100644 --- a/xarray/core/resample_cftime.py +++ b/xarray/core/resample_cftime.py @@ -43,7 +43,7 @@ import numpy as np import pandas as pd -from ..coding.cftime_offsets import ( +from xarray.coding.cftime_offsets import ( BaseCFTimeOffset, Day, MonthEnd, @@ -54,11 +54,11 @@ normalize_date, to_offset, ) -from ..coding.cftimeindex import CFTimeIndex -from .types import SideOptions +from xarray.coding.cftimeindex import CFTimeIndex +from xarray.core.types import SideOptions if typing.TYPE_CHECKING: - from .types import CFTimeDatetime + from xarray.core.types import CFTimeDatetime class CFTimeGrouper: diff --git a/xarray/core/rolling.py b/xarray/core/rolling.py index f7a573019ae..c06a2b40b21 100644 --- a/xarray/core/rolling.py +++ b/xarray/core/rolling.py @@ -17,12 +17,12 @@ import numpy as np -from . import dtypes, duck_array_ops, utils -from .arithmetic import CoarsenArithmetic -from .options import OPTIONS, _get_keep_attrs -from .pycompat import is_duck_dask_array -from .types import CoarsenBoundaryOptions, SideOptions, T_Xarray -from .utils import either_dict_or_kwargs +from xarray.core import dtypes, duck_array_ops, utils +from xarray.core.arithmetic import CoarsenArithmetic +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.types import CoarsenBoundaryOptions, SideOptions, T_Xarray +from xarray.core.utils import either_dict_or_kwargs try: import bottleneck @@ -31,8 +31,8 @@ bottleneck = None if TYPE_CHECKING: - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset RollingKey = Any _T = TypeVar("_T") @@ -372,7 +372,7 @@ def _construct( keep_attrs: bool | None = None, **window_dim_kwargs: Hashable, ) -> DataArray: - from .dataarray import DataArray + from xarray.core.dataarray import DataArray keep_attrs = self._get_keep_attrs(keep_attrs) @@ -506,7 +506,7 @@ def _counts(self, keep_attrs: bool | None) -> DataArray: return counts def _bottleneck_reduce(self, func, keep_attrs, **kwargs): - from .dataarray import DataArray + from xarray.core.dataarray import DataArray # bottleneck doesn't allow min_count to be 0, although it should # work the same as if min_count = 1 @@ -649,7 +649,7 @@ def __init__( self.rollings[key] = DataArrayRolling(da, w, min_periods, center) def _dataset_implementation(self, func, keep_attrs, **kwargs): - from .dataset import Dataset + from xarray.core.dataset import Dataset keep_attrs = self._get_keep_attrs(keep_attrs) @@ -749,7 +749,7 @@ def construct( Dataset with variables converted from rolling object. """ - from .dataset import Dataset + from xarray.core.dataset import Dataset keep_attrs = self._get_keep_attrs(keep_attrs) @@ -918,8 +918,8 @@ def construct( DatasetRolling.construct """ - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset window_dim = either_dict_or_kwargs( window_dim, window_dim_kwargs, "Coarsen.construct" @@ -1004,7 +1004,7 @@ def _reduce_method( def wrapped_func( self: DataArrayCoarsen, keep_attrs: bool | None = None, **kwargs ) -> DataArray: - from .dataarray import DataArray + from xarray.core.dataarray import DataArray keep_attrs = self._get_keep_attrs(keep_attrs) @@ -1092,7 +1092,7 @@ def _reduce_method( def wrapped_func( self: DatasetCoarsen, keep_attrs: bool | None = None, **kwargs ) -> Dataset: - from .dataset import Dataset + from xarray.core.dataset import Dataset keep_attrs = self._get_keep_attrs(keep_attrs) diff --git a/xarray/core/rolling_exp.py b/xarray/core/rolling_exp.py index 6033b061335..faf81c8de13 100644 --- a/xarray/core/rolling_exp.py +++ b/xarray/core/rolling_exp.py @@ -5,10 +5,10 @@ import numpy as np from packaging.version import Version -from .options import _get_keep_attrs -from .pdcompat import count_not_none -from .pycompat import is_duck_dask_array -from .types import T_DataWithCoords +from xarray.core.options import _get_keep_attrs +from xarray.core.pdcompat import count_not_none +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.types import T_DataWithCoords def _get_alpha(com=None, span=None, halflife=None, alpha=None): diff --git a/xarray/core/types.py b/xarray/core/types.py index adf046dabb2..220aeb8da7a 100644 --- a/xarray/core/types.py +++ b/xarray/core/types.py @@ -24,13 +24,13 @@ if TYPE_CHECKING: from numpy.typing import ArrayLike - from ..backends.common import BackendEntrypoint - from .common import AbstractArray, DataWithCoords - from .dataarray import DataArray - from .dataset import Dataset - from .groupby import DataArrayGroupBy, GroupBy - from .indexes import Index - from .variable import Variable + from xarray.backends.common import BackendEntrypoint + from xarray.core.common import AbstractArray, DataWithCoords + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.groupby import DataArrayGroupBy, GroupBy + from xarray.core.indexes import Index + from xarray.core.variable import Variable try: from dask.array import Array as DaskArray diff --git a/xarray/core/utils.py b/xarray/core/utils.py index 7ecb73049d1..86c644de5f0 100644 --- a/xarray/core/utils.py +++ b/xarray/core/utils.py @@ -71,7 +71,7 @@ import pandas as pd if TYPE_CHECKING: - from .types import Dims, ErrorOptionsWithWarn, OrderedDims + from xarray.core.types import Dims, ErrorOptionsWithWarn, OrderedDims K = TypeVar("K") V = TypeVar("V") @@ -125,7 +125,7 @@ def maybe_coerce_to_str(index, original_coords): pd.Index uses object-dtype to store str - try to avoid this for coords """ - from . import dtypes + from xarray.core import dtypes try: result_type = dtypes.result_type(*original_coords) @@ -157,7 +157,7 @@ def equivalent(first: T, second: T) -> bool: equivalent is sequentially called on all the elements. """ # TODO: refactor to avoid circular import - from . import duck_array_ops + from xarray.core import duck_array_ops if first is second: return True @@ -285,7 +285,7 @@ def either_dict_or_kwargs( def _is_scalar(value, include_0d): - from .variable import NON_NUMPY_SUPPORTED_ARRAY_TYPES + from xarray.core.variable import NON_NUMPY_SUPPORTED_ARRAY_TYPES if include_0d: include_0d = getattr(value, "ndim", None) == 0 @@ -1129,8 +1129,8 @@ def contains_only_dask_or_numpy(obj) -> bool: """Returns True if xarray object contains only numpy or dask arrays. Expects obj to be Dataset or DataArray""" - from .dataarray import DataArray - from .pycompat import is_duck_dask_array + from xarray.core.dataarray import DataArray + from xarray.core.pycompat import is_duck_dask_array if isinstance(obj, DataArray): obj = obj._to_temp_dataset() diff --git a/xarray/core/variable.py b/xarray/core/variable.py index bb988392f50..d3db3fb2dd6 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -24,20 +24,19 @@ from packaging.version import Version import xarray as xr # only for Dataset and DataArray - -from . import common, dtypes, duck_array_ops, indexing, nputils, ops, utils -from .arithmetic import VariableArithmetic -from .common import AbstractArray -from .indexing import ( +from xarray.core import common, dtypes, duck_array_ops, indexing, nputils, ops, utils +from xarray.core.arithmetic import VariableArithmetic +from xarray.core.common import AbstractArray +from xarray.core.indexing import ( BasicIndexer, OuterIndexer, PandasIndexingAdapter, VectorizedIndexer, as_indexable, ) -from .options import OPTIONS, _get_keep_attrs -from .pycompat import array_type, integer_types, is_duck_dask_array -from .utils import ( +from xarray.core.options import OPTIONS, _get_keep_attrs +from xarray.core.pycompat import array_type, integer_types, is_duck_dask_array +from xarray.core.utils import ( Frozen, NdimSizeLenMixin, OrderedSet, @@ -59,7 +58,7 @@ BASIC_INDEXING_TYPES = integer_types + (slice,) if TYPE_CHECKING: - from .types import ( + from xarray.core.types import ( Dims, ErrorOptionsWithWarn, PadModeOptions, @@ -112,7 +111,7 @@ def as_variable(obj, name=None) -> Variable | IndexVariable: The newly created variable. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray # TODO: consider extending this method to automatically handle Iris and if isinstance(obj, DataArray): @@ -248,7 +247,7 @@ def as_compatible_data(data, fastpath=False): Finally, wrap it up with an adapter if necessary. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if fastpath and getattr(data, "ndim", 0) > 0: # can't use fastpath (yet) for scalars @@ -505,7 +504,7 @@ def astype( dask.array.Array.astype sparse.COO.astype """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc kwargs = dict(order=order, casting=casting, subok=subok, copy=copy) kwargs = {k: v for k, v in kwargs.items() if v is not None} @@ -1882,7 +1881,7 @@ def clip(self, min=None, max=None): -------- numpy.clip : equivalent function """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc return apply_ufunc(np.clip, self, min, max, dask="allowed") @@ -2029,7 +2028,7 @@ def concat( Concatenated Variable formed by stacking all the supplied variables along the given dimension. """ - from .merge import merge_attrs + from xarray.core.merge import merge_attrs if not isinstance(dim, str): (dim,) = dim.dims @@ -2197,7 +2196,7 @@ def quantile( The American Statistician, 50(4), pp. 361-365, 1996 """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc if interpolation is not None: warnings.warn( @@ -2544,7 +2543,7 @@ def isnull(self, keep_attrs: bool | None = None): array([False, True, False]) """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc if keep_attrs is None: keep_attrs = _get_keep_attrs(default=False) @@ -2578,7 +2577,7 @@ def notnull(self, keep_attrs: bool | None = None): array([ True, False, True]) """ - from .computation import apply_ufunc + from xarray.core.computation import apply_ufunc if keep_attrs is None: keep_attrs = _get_keep_attrs(default=False) @@ -2904,7 +2903,7 @@ def concat( This exists because we want to avoid converting Index objects to NumPy arrays, if possible. """ - from .merge import merge_attrs + from xarray.core.merge import merge_attrs if not isinstance(dim, str): (dim,) = dim.dims diff --git a/xarray/core/weighted.py b/xarray/core/weighted.py index 0f3a9aa3432..fc6f280b596 100644 --- a/xarray/core/weighted.py +++ b/xarray/core/weighted.py @@ -5,11 +5,11 @@ import numpy as np from numpy.typing import ArrayLike -from . import duck_array_ops, utils -from .alignment import align, broadcast -from .computation import apply_ufunc, dot -from .pycompat import is_duck_dask_array -from .types import Dims, T_Xarray +from xarray.core import duck_array_ops, utils +from xarray.core.alignment import align, broadcast +from xarray.core.computation import apply_ufunc, dot +from xarray.core.pycompat import is_duck_dask_array +from xarray.core.types import Dims, T_Xarray # Weighted quantile methods are a subset of the numpy supported quantile methods. QUANTILE_METHODS = Literal[ @@ -125,8 +125,8 @@ if TYPE_CHECKING: - from .dataarray import DataArray - from .dataset import Dataset + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset class Weighted(Generic[T_Xarray]): @@ -162,7 +162,7 @@ def __init__(self, obj: T_Xarray, weights: DataArray) -> None: Missing values can be replaced by ``weights.fillna(0)``. """ - from .dataarray import DataArray + from xarray.core.dataarray import DataArray if not isinstance(weights, DataArray): raise ValueError("`weights` must be a DataArray") diff --git a/xarray/indexes/__init__.py b/xarray/indexes/__init__.py index 41321c9a0ff..143d7a58fda 100644 --- a/xarray/indexes/__init__.py +++ b/xarray/indexes/__init__.py @@ -2,6 +2,6 @@ DataArray objects. """ -from ..core.indexes import Index, PandasIndex, PandasMultiIndex +from xarray.core.indexes import Index, PandasIndex, PandasMultiIndex __all__ = ["Index", "PandasIndex", "PandasMultiIndex"] diff --git a/xarray/plot/__init__.py b/xarray/plot/__init__.py index bac62673ee1..28aac6edd9e 100644 --- a/xarray/plot/__init__.py +++ b/xarray/plot/__init__.py @@ -6,7 +6,7 @@ DataArray.plot._____ Dataset.plot._____ """ -from .dataarray_plot import ( +from xarray.plot.dataarray_plot import ( contour, contourf, hist, @@ -17,8 +17,8 @@ step, surface, ) -from .dataset_plot import scatter -from .facetgrid import FacetGrid +from xarray.plot.dataset_plot import scatter +from xarray.plot.facetgrid import FacetGrid __all__ = [ "plot", diff --git a/xarray/plot/accessor.py b/xarray/plot/accessor.py index 273d0f4f921..62a02400222 100644 --- a/xarray/plot/accessor.py +++ b/xarray/plot/accessor.py @@ -6,7 +6,7 @@ import numpy as np # Accessor methods have the same name as plotting methods, so we need a different namespace -from . import dataarray_plot, dataset_plot +from xarray.plot import dataarray_plot, dataset_plot if TYPE_CHECKING: from matplotlib.axes import Axes @@ -19,10 +19,10 @@ from mpl_toolkits.mplot3d.art3d import Line3D, Poly3DCollection from numpy.typing import ArrayLike - from ..core.dataarray import DataArray - from ..core.dataset import Dataset - from ..core.types import AspectOptions, HueStyleOptions, ScaleOptions - from .facetgrid import FacetGrid + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import AspectOptions, HueStyleOptions, ScaleOptions + from xarray.plot.facetgrid import FacetGrid class DataArrayPlotAccessor: diff --git a/xarray/plot/dataarray_plot.py b/xarray/plot/dataarray_plot.py index 46aaf33f683..f1e41478d4c 100644 --- a/xarray/plot/dataarray_plot.py +++ b/xarray/plot/dataarray_plot.py @@ -18,10 +18,10 @@ import pandas as pd from packaging.version import Version -from ..core.alignment import broadcast -from ..core.concat import concat -from .facetgrid import _easy_facetgrid -from .utils import ( +from xarray.core.alignment import broadcast +from xarray.core.concat import concat +from xarray.plot.facetgrid import _easy_facetgrid +from xarray.plot.utils import ( _LINEWIDTH_RANGE, _MARKERSIZE_RANGE, _add_colorbar, @@ -52,15 +52,15 @@ from mpl_toolkits.mplot3d.art3d import Line3D, Poly3DCollection from numpy.typing import ArrayLike - from ..core.dataarray import DataArray - from ..core.types import ( + from xarray.core.dataarray import DataArray + from xarray.core.types import ( AspectOptions, ExtendOptions, HueStyleOptions, ScaleOptions, T_DataArray, ) - from .facetgrid import FacetGrid + from xarray.plot.facetgrid import FacetGrid def _infer_line_data( diff --git a/xarray/plot/dataset_plot.py b/xarray/plot/dataset_plot.py index 55819b0ab9f..88d05b34a2b 100644 --- a/xarray/plot/dataset_plot.py +++ b/xarray/plot/dataset_plot.py @@ -5,10 +5,10 @@ import warnings from typing import TYPE_CHECKING, Any, Callable, Hashable, Iterable, TypeVar, overload -from ..core.alignment import broadcast -from . import dataarray_plot -from .facetgrid import _easy_facetgrid -from .utils import ( +from xarray.core.alignment import broadcast +from xarray.plot import dataarray_plot +from xarray.plot.facetgrid import _easy_facetgrid +from xarray.plot.utils import ( _add_colorbar, _get_nice_quiver_magnitude, _infer_meta_data, @@ -23,10 +23,15 @@ from matplotlib.quiver import Quiver from numpy.typing import ArrayLike - from ..core.dataarray import DataArray - from ..core.dataset import Dataset - from ..core.types import AspectOptions, ExtendOptions, HueStyleOptions, ScaleOptions - from .facetgrid import FacetGrid + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import ( + AspectOptions, + ExtendOptions, + HueStyleOptions, + ScaleOptions, + ) + from xarray.plot.facetgrid import FacetGrid def _dsplot(plotfunc): @@ -703,7 +708,7 @@ def wrapper(dataset_plotfunc: F) -> F: def _normalize_args( plotmethod: str, args: tuple[Any, ...], kwargs: dict[str, Any] ) -> dict[str, Any]: - from ..core.dataarray import DataArray + from xarray.core.dataarray import DataArray # Determine positional arguments keyword by inspecting the # signature of the plotmethod: @@ -719,7 +724,7 @@ def _normalize_args( def _temp_dataarray(ds: Dataset, y: Hashable, locals_: dict[str, Any]) -> DataArray: """Create a temporary datarray with extra coords.""" - from ..core.dataarray import DataArray + from xarray.core.dataarray import DataArray # Base coords: coords = dict(ds.coords) diff --git a/xarray/plot/facetgrid.py b/xarray/plot/facetgrid.py index 91b0deba454..c510b0767ba 100644 --- a/xarray/plot/facetgrid.py +++ b/xarray/plot/facetgrid.py @@ -17,9 +17,9 @@ import numpy as np -from ..core.formatting import format_item -from ..core.types import HueStyleOptions, T_Xarray -from .utils import ( +from xarray.core.formatting import format_item +from xarray.core.types import HueStyleOptions, T_Xarray +from xarray.plot.utils import ( _LINEWIDTH_RANGE, _MARKERSIZE_RANGE, _add_legend, @@ -42,7 +42,7 @@ from matplotlib.quiver import QuiverKey from matplotlib.text import Annotation - from ..core.dataarray import DataArray + from xarray.core.dataarray import DataArray # Overrides axes.labelsize, xtick.major.size, ytick.major.size @@ -564,7 +564,7 @@ def map_dataarray_line( _labels=None, **kwargs: Any, ) -> T_FacetGrid: - from .dataarray_plot import _infer_line_data + from xarray.plot.dataarray_plot import _infer_line_data for d, ax in zip(self.name_dicts.flat, self.axs.flat): # None is the sentinel value @@ -606,7 +606,7 @@ def map_dataset( add_guide: bool | None = None, **kwargs: Any, ) -> T_FacetGrid: - from .dataset_plot import _infer_meta_data + from xarray.plot.dataset_plot import _infer_meta_data kwargs["add_guide"] = False @@ -821,7 +821,7 @@ def _set_lims( def set_axis_labels(self, *axlabels: Hashable) -> None: """Set axis labels on the left column and bottom row of the grid.""" - from ..core.dataarray import DataArray + from xarray.core.dataarray import DataArray for var, axis in zip(axlabels, ["x", "y", "z"]): if var is not None: diff --git a/xarray/plot/utils.py b/xarray/plot/utils.py index ba5ea736bbd..46d180447d8 100644 --- a/xarray/plot/utils.py +++ b/xarray/plot/utils.py @@ -19,10 +19,10 @@ import numpy as np import pandas as pd -from ..core.indexes import PandasMultiIndex -from ..core.options import OPTIONS -from ..core.pycompat import DuckArrayModule -from ..core.utils import is_scalar, module_available +from xarray.core.indexes import PandasMultiIndex +from xarray.core.options import OPTIONS +from xarray.core.pycompat import DuckArrayModule +from xarray.core.utils import is_scalar, module_available nc_time_axis_available = module_available("nc_time_axis") @@ -39,9 +39,9 @@ from matplotlib.ticker import FuncFormatter from numpy.typing import ArrayLike - from ..core.dataarray import DataArray - from ..core.dataset import Dataset - from ..core.types import AspectOptions, ScaleOptions + from xarray.core.dataarray import DataArray + from xarray.core.dataset import Dataset + from xarray.core.types import AspectOptions, ScaleOptions try: import matplotlib.pyplot as plt diff --git a/xarray/tests/conftest.py b/xarray/tests/conftest.py index 658c349cd74..6a8cf008f9f 100644 --- a/xarray/tests/conftest.py +++ b/xarray/tests/conftest.py @@ -3,8 +3,7 @@ import pytest from xarray import DataArray, Dataset - -from . import create_test_data, requires_dask +from xarray.tests import create_test_data, requires_dask @pytest.fixture(params=["numpy", pytest.param("dask", marks=requires_dask)]) diff --git a/xarray/tests/test_accessor_dt.py b/xarray/tests/test_accessor_dt.py index ddbcc34b636..eecacd6fd23 100644 --- a/xarray/tests/test_accessor_dt.py +++ b/xarray/tests/test_accessor_dt.py @@ -5,8 +5,7 @@ import pytest import xarray as xr - -from . import ( +from xarray.tests import ( assert_array_equal, assert_chunks_equal, assert_equal, @@ -537,7 +536,7 @@ def test_dask_field_access(times_3d, data, field) -> None: @pytest.fixture() def cftime_date_type(calendar): - from .test_coding_times import _all_cftime_date_types + from xarray.tests.test_coding_times import _all_cftime_date_types return _all_cftime_date_types()[calendar] diff --git a/xarray/tests/test_accessor_str.py b/xarray/tests/test_accessor_str.py index 6c9705cdaa4..168d3232f81 100644 --- a/xarray/tests/test_accessor_str.py +++ b/xarray/tests/test_accessor_str.py @@ -45,8 +45,7 @@ import pytest import xarray as xr - -from . import assert_equal, assert_identical, requires_dask +from xarray.tests import assert_equal, assert_identical, requires_dask @pytest.fixture( diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py index 81417f8a06a..b923184800e 100644 --- a/xarray/tests/test_backends.py +++ b/xarray/tests/test_backends.py @@ -50,9 +50,7 @@ from xarray.core import indexing from xarray.core.options import set_options from xarray.core.pycompat import array_type -from xarray.tests import mock - -from . import ( +from xarray.tests import ( arm_xfail, assert_allclose, assert_array_equal, @@ -63,6 +61,7 @@ has_h5netcdf_0_12, has_netCDF4, has_scipy, + mock, network, requires_cfgrib, requires_cftime, @@ -80,12 +79,12 @@ requires_scipy_or_netCDF4, requires_zarr, ) -from .test_coding_times import ( +from xarray.tests.test_coding_times import ( _ALL_CALENDARS, _NON_STANDARD_CALENDARS, _STANDARD_CALENDARS, ) -from .test_dataset import ( +from xarray.tests.test_dataset import ( create_append_string_length_mismatch_test_data, create_append_test_data, create_test_data, @@ -539,7 +538,7 @@ def test_roundtrip_numpy_datetime_data(self) -> None: @requires_cftime def test_roundtrip_cftime_datetime_data(self) -> None: - from .test_coding_times import _all_cftime_date_types + from xarray.tests.test_coding_times import _all_cftime_date_types date_types = _all_cftime_date_types() for date_type in date_types.values(): @@ -3604,7 +3603,7 @@ def test_roundtrip_numpy_datetime_data(self) -> None: def test_roundtrip_cftime_datetime_data(self) -> None: # Override method in DatasetIOBase - remove not applicable # save_kwargs - from .test_coding_times import _all_cftime_date_types + from xarray.tests.test_coding_times import _all_cftime_date_types date_types = _all_cftime_date_types() for date_type in date_types.values(): diff --git a/xarray/tests/test_backends_api.py b/xarray/tests/test_backends_api.py index efff86d7683..befc4cbaf04 100644 --- a/xarray/tests/test_backends_api.py +++ b/xarray/tests/test_backends_api.py @@ -7,8 +7,7 @@ import xarray as xr from xarray.backends.api import _get_default_engine - -from . import ( +from xarray.tests import ( assert_identical, assert_no_warnings, requires_dask, diff --git a/xarray/tests/test_calendar_ops.py b/xarray/tests/test_calendar_ops.py index ff791a03505..d118ccf4556 100644 --- a/xarray/tests/test_calendar_ops.py +++ b/xarray/tests/test_calendar_ops.py @@ -7,8 +7,7 @@ from xarray.coding.calendar_ops import convert_calendar, interp_calendar from xarray.coding.cftime_offsets import date_range from xarray.testing import assert_identical - -from . import requires_cftime +from xarray.tests import requires_cftime cftime = pytest.importorskip("cftime") diff --git a/xarray/tests/test_cftime_offsets.py b/xarray/tests/test_cftime_offsets.py index d28f4594559..c981015521b 100644 --- a/xarray/tests/test_cftime_offsets.py +++ b/xarray/tests/test_cftime_offsets.py @@ -33,8 +33,7 @@ ) from xarray.coding.frequencies import infer_freq from xarray.core.dataarray import DataArray - -from . import _CFTIME_CALENDARS, requires_cftime +from xarray.tests import _CFTIME_CALENDARS, requires_cftime cftime = pytest.importorskip("cftime") diff --git a/xarray/tests/test_cftimeindex.py b/xarray/tests/test_cftimeindex.py index 639594d6829..a27c7f99dfc 100644 --- a/xarray/tests/test_cftimeindex.py +++ b/xarray/tests/test_cftimeindex.py @@ -18,10 +18,13 @@ assert_all_valid_date_type, parse_iso8601_like, ) -from xarray.tests import assert_array_equal, assert_identical - -from . import has_cftime, requires_cftime -from .test_coding_times import ( +from xarray.tests import ( + assert_array_equal, + assert_identical, + has_cftime, + requires_cftime, +) +from xarray.tests.test_coding_times import ( _ALL_CALENDARS, _NON_STANDARD_CALENDARS, _all_cftime_date_types, diff --git a/xarray/tests/test_coarsen.py b/xarray/tests/test_coarsen.py index 542f6815597..a46d10bd0f6 100644 --- a/xarray/tests/test_coarsen.py +++ b/xarray/tests/test_coarsen.py @@ -6,8 +6,7 @@ import xarray as xr from xarray import DataArray, Dataset, set_options - -from . import ( +from xarray.tests import ( assert_allclose, assert_equal, assert_identical, diff --git a/xarray/tests/test_coding.py b/xarray/tests/test_coding.py index 3af43f78e38..5bf23819d87 100644 --- a/xarray/tests/test_coding.py +++ b/xarray/tests/test_coding.py @@ -9,8 +9,7 @@ import xarray as xr from xarray.coding import variables from xarray.conventions import decode_cf_variable, encode_cf_variable - -from . import assert_allclose, assert_equal, assert_identical, requires_dask +from xarray.tests import assert_allclose, assert_equal, assert_identical, requires_dask with suppress(ImportError): import dask.array as da diff --git a/xarray/tests/test_coding_strings.py b/xarray/tests/test_coding_strings.py index 92199884a03..cb9595f4a64 100644 --- a/xarray/tests/test_coding_strings.py +++ b/xarray/tests/test_coding_strings.py @@ -8,8 +8,12 @@ from xarray import Variable from xarray.coding import strings from xarray.core import indexing - -from . import IndexerMaker, assert_array_equal, assert_identical, requires_dask +from xarray.tests import ( + IndexerMaker, + assert_array_equal, + assert_identical, + requires_dask, +) with suppress(ImportError): import dask.array as da diff --git a/xarray/tests/test_coding_times.py b/xarray/tests/test_coding_times.py index ca3b93728aa..79eab1ccbf1 100644 --- a/xarray/tests/test_coding_times.py +++ b/xarray/tests/test_coding_times.py @@ -30,8 +30,7 @@ from xarray.conventions import _update_bounds_attributes, cf_encoder from xarray.core.common import contains_cftime_datetimes from xarray.testing import assert_equal, assert_identical - -from . import ( +from xarray.tests import ( arm_xfail, assert_array_equal, assert_no_warnings, diff --git a/xarray/tests/test_combine.py b/xarray/tests/test_combine.py index 0e43868d488..66da86459a1 100644 --- a/xarray/tests/test_combine.py +++ b/xarray/tests/test_combine.py @@ -25,9 +25,8 @@ _infer_concat_order_from_positions, _new_tile_id, ) - -from . import assert_equal, assert_identical, requires_cftime -from .test_dataset import create_test_data +from xarray.tests import assert_equal, assert_identical, requires_cftime +from xarray.tests.test_dataset import create_test_data def assert_combined_tile_ids_equal(dict1, dict2): diff --git a/xarray/tests/test_computation.py b/xarray/tests/test_computation.py index 73889c362fe..a4384b1de91 100644 --- a/xarray/tests/test_computation.py +++ b/xarray/tests/test_computation.py @@ -24,8 +24,12 @@ unified_dim_sizes, ) from xarray.core.pycompat import mod_version - -from . import has_dask, raise_if_dask_computes, requires_cftime, requires_dask +from xarray.tests import ( + has_dask, + raise_if_dask_computes, + requires_cftime, + requires_dask, +) dask_version = mod_version("dask") diff --git a/xarray/tests/test_concat.py b/xarray/tests/test_concat.py index b199c697b21..e0e0038cd89 100644 --- a/xarray/tests/test_concat.py +++ b/xarray/tests/test_concat.py @@ -10,15 +10,14 @@ from xarray import DataArray, Dataset, Variable, concat from xarray.core import dtypes, merge from xarray.core.indexes import PandasIndex - -from . import ( +from xarray.tests import ( InaccessibleArray, assert_array_equal, assert_equal, assert_identical, requires_dask, ) -from .test_dataset import create_test_data +from xarray.tests.test_dataset import create_test_data if TYPE_CHECKING: from xarray.core.types import CombineAttrsOptions, JoinOptions diff --git a/xarray/tests/test_conventions.py b/xarray/tests/test_conventions.py index cc18272be72..9485b506b89 100644 --- a/xarray/tests/test_conventions.py +++ b/xarray/tests/test_conventions.py @@ -20,9 +20,13 @@ from xarray.backends.memory import InMemoryDataStore from xarray.conventions import decode_cf from xarray.testing import assert_identical - -from . import assert_array_equal, requires_cftime, requires_dask, requires_netCDF4 -from .test_backends import CFEncodedBase +from xarray.tests import ( + assert_array_equal, + requires_cftime, + requires_dask, + requires_netCDF4, +) +from xarray.tests.test_backends import CFEncodedBase class TestBoolTypeArray: diff --git a/xarray/tests/test_dask.py b/xarray/tests/test_dask.py index 24b3ef94cd0..452e08b15d4 100644 --- a/xarray/tests/test_dask.py +++ b/xarray/tests/test_dask.py @@ -14,22 +14,21 @@ import xarray as xr from xarray import DataArray, Dataset, Variable from xarray.core import duck_array_ops +from xarray.core.duck_array_ops import lazy_array_equiv from xarray.core.pycompat import mod_version from xarray.testing import assert_chunks_equal -from xarray.tests import mock - -from ..core.duck_array_ops import lazy_array_equiv -from . import ( +from xarray.tests import ( assert_allclose, assert_array_equal, assert_equal, assert_frame_equal, assert_identical, + mock, raise_if_dask_computes, requires_pint, requires_scipy_or_netCDF4, ) -from .test_backends import create_tmp_file +from xarray.tests.test_backends import create_tmp_file dask = pytest.importorskip("dask") da = pytest.importorskip("dask.array") @@ -1429,7 +1428,7 @@ def test_map_blocks_hlg_layers(): def test_make_meta(map_ds): - from ..core.parallel import make_meta + from xarray.core.parallel import make_meta meta = make_meta(map_ds) diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index 6bf3a2e3aa4..0d3be9d378b 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -34,8 +34,7 @@ from xarray.core.indexes import Index, PandasIndex from xarray.core.pycompat import array_type, integer_types from xarray.core.utils import is_scalar - -from . import ( +from xarray.tests import ( InaccessibleArray, UnexpectedDataAccess, assert_allclose, diff --git a/xarray/tests/test_distributed.py b/xarray/tests/test_distributed.py index 2dd589fd872..1c7f1c94019 100644 --- a/xarray/tests/test_distributed.py +++ b/xarray/tests/test_distributed.py @@ -36,7 +36,7 @@ ) from xarray.tests.test_dataset import create_test_data -from . import ( +from xarray.tests import ( assert_allclose, assert_identical, has_h5netcdf, diff --git a/xarray/tests/test_duck_array_ops.py b/xarray/tests/test_duck_array_ops.py index 7b271108ed9..2943bd71671 100644 --- a/xarray/tests/test_duck_array_ops.py +++ b/xarray/tests/test_duck_array_ops.py @@ -29,8 +29,7 @@ ) from xarray.core.pycompat import array_type from xarray.testing import assert_allclose, assert_equal, assert_identical - -from . import ( +from xarray.tests import ( arm_xfail, assert_array_equal, has_dask, diff --git a/xarray/tests/test_extensions.py b/xarray/tests/test_extensions.py index d4414b1f53a..7e1802246c7 100644 --- a/xarray/tests/test_extensions.py +++ b/xarray/tests/test_extensions.py @@ -5,8 +5,7 @@ import pytest import xarray as xr - -from . import assert_identical +from xarray.tests import assert_identical @xr.register_dataset_accessor("example_accessor") diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index c8b759da32c..48917c9c19b 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -10,8 +10,7 @@ import xarray as xr from xarray.core import formatting - -from . import requires_dask, requires_netCDF4 +from xarray.tests import requires_dask, requires_netCDF4 class TestFormatting: diff --git a/xarray/tests/test_groupby.py b/xarray/tests/test_groupby.py index 335f31de7b7..3b214f43d69 100644 --- a/xarray/tests/test_groupby.py +++ b/xarray/tests/test_groupby.py @@ -10,8 +10,7 @@ import xarray as xr from xarray import DataArray, Dataset, Variable from xarray.core.groupby import _consolidate_slices - -from . import ( +from xarray.tests import ( assert_allclose, assert_array_equal, assert_equal, diff --git a/xarray/tests/test_indexes.py b/xarray/tests/test_indexes.py index f9ca1d1bc2e..3ecfa73cc89 100644 --- a/xarray/tests/test_indexes.py +++ b/xarray/tests/test_indexes.py @@ -20,9 +20,8 @@ safe_cast_to_index, ) from xarray.core.variable import IndexVariable, Variable - -from . import assert_array_equal, assert_identical, requires_cftime -from .test_coding_times import _all_cftime_date_types +from xarray.tests import assert_array_equal, assert_identical, requires_cftime +from xarray.tests.test_coding_times import _all_cftime_date_types def test_asarray_tuplesafe() -> None: diff --git a/xarray/tests/test_indexing.py b/xarray/tests/test_indexing.py index 24f9e3b085d..b28aebe6830 100644 --- a/xarray/tests/test_indexing.py +++ b/xarray/tests/test_indexing.py @@ -11,8 +11,7 @@ from xarray.core import indexing, nputils from xarray.core.indexes import PandasIndex, PandasMultiIndex from xarray.core.types import T_Xarray - -from . import IndexerMaker, ReturnItem, assert_array_equal +from xarray.tests import IndexerMaker, ReturnItem, assert_array_equal B = IndexerMaker(indexing.BasicIndexer) diff --git a/xarray/tests/test_interp.py b/xarray/tests/test_interp.py index b3c94e33efb..386b26bbc7e 100644 --- a/xarray/tests/test_interp.py +++ b/xarray/tests/test_interp.py @@ -8,19 +8,19 @@ import pytest import xarray as xr +from xarray.coding.cftimeindex import _parse_array_of_cftime_strings from xarray.core.types import InterpOptions from xarray.tests import ( assert_allclose, assert_equal, assert_identical, + has_dask, + has_scipy, requires_cftime, requires_dask, requires_scipy, ) - -from ..coding.cftimeindex import _parse_array_of_cftime_strings -from . import has_dask, has_scipy -from .test_dataset import create_test_data +from xarray.tests.test_dataset import create_test_data try: import scipy diff --git a/xarray/tests/test_merge.py b/xarray/tests/test_merge.py index 3c8b12b5257..8957f9c829a 100644 --- a/xarray/tests/test_merge.py +++ b/xarray/tests/test_merge.py @@ -7,8 +7,7 @@ from xarray.core import dtypes, merge from xarray.core.merge import MergeError from xarray.testing import assert_equal, assert_identical - -from .test_dataset import create_test_data +from xarray.tests.test_dataset import create_test_data class TestMergeInternals: diff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py index d4a707b4e23..8d69fb46342 100644 --- a/xarray/tests/test_plot.py +++ b/xarray/tests/test_plot.py @@ -26,8 +26,7 @@ get_axis, label_from_attrs, ) - -from . import ( +from xarray.tests import ( assert_array_equal, assert_equal, requires_cartopy, @@ -2605,7 +2604,7 @@ def setUp(self) -> None: self.ds = ds def test_accessor(self) -> None: - from ..plot.accessor import DatasetPlotAccessor + from xarray.plot.accessor import DatasetPlotAccessor assert Dataset.plot is DatasetPlotAccessor assert isinstance(self.ds.plot, DatasetPlotAccessor) diff --git a/xarray/tests/test_sparse.py b/xarray/tests/test_sparse.py index 71e4701c367..fd48bab5f41 100644 --- a/xarray/tests/test_sparse.py +++ b/xarray/tests/test_sparse.py @@ -12,8 +12,7 @@ import xarray as xr from xarray import DataArray, Variable from xarray.core.pycompat import array_type, mod_version - -from . import assert_equal, assert_identical, requires_dask +from xarray.tests import assert_equal, assert_identical, requires_dask filterwarnings = pytest.mark.filterwarnings param = pytest.param diff --git a/xarray/tests/test_testing.py b/xarray/tests/test_testing.py index df78b876965..59861ef7981 100644 --- a/xarray/tests/test_testing.py +++ b/xarray/tests/test_testing.py @@ -6,8 +6,7 @@ import pytest import xarray as xr - -from . import has_dask +from xarray.tests import has_dask try: from dask.array import from_array as dask_from_array diff --git a/xarray/tests/test_tutorial.py b/xarray/tests/test_tutorial.py index 3f55bff278a..9d59219c204 100644 --- a/xarray/tests/test_tutorial.py +++ b/xarray/tests/test_tutorial.py @@ -3,8 +3,7 @@ import pytest from xarray import DataArray, tutorial - -from . import assert_identical, network +from xarray.tests import assert_identical, network @network diff --git a/xarray/tests/test_ufuncs.py b/xarray/tests/test_ufuncs.py index d730746bd60..f463471b55c 100644 --- a/xarray/tests/test_ufuncs.py +++ b/xarray/tests/test_ufuncs.py @@ -4,10 +4,9 @@ import pytest import xarray as xr - -from . import assert_array_equal -from . import assert_identical as assert_identical_ -from . import mock +from xarray.tests import assert_array_equal +from xarray.tests import assert_identical as assert_identical_ +from xarray.tests import mock def assert_identical(a, b): diff --git a/xarray/tests/test_units.py b/xarray/tests/test_units.py index 9a27989778a..9e872c93c0c 100644 --- a/xarray/tests/test_units.py +++ b/xarray/tests/test_units.py @@ -10,8 +10,7 @@ import xarray as xr from xarray.core import dtypes, duck_array_ops - -from . import ( +from xarray.tests import ( assert_allclose, assert_duckarray_allclose, assert_equal, @@ -19,8 +18,8 @@ requires_dask, requires_matplotlib, ) -from .test_plot import PlotTestCase -from .test_variable import _PAD_XR_NP_ARGS +from xarray.tests.test_plot import PlotTestCase +from xarray.tests.test_variable import _PAD_XR_NP_ARGS try: import matplotlib.pyplot as plt diff --git a/xarray/tests/test_utils.py b/xarray/tests/test_utils.py index a1a9a41d782..c1aab2801dd 100644 --- a/xarray/tests/test_utils.py +++ b/xarray/tests/test_utils.py @@ -8,8 +8,7 @@ from xarray.core import duck_array_ops, utils from xarray.core.utils import either_dict_or_kwargs, iterate_nested - -from . import assert_array_equal, requires_dask +from xarray.tests import assert_array_equal, requires_dask class TestAlias: diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index 3a6c8f1b966..c82a8c3a539 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -28,9 +28,7 @@ from xarray.core.pycompat import array_type from xarray.core.utils import NDArrayMixin from xarray.core.variable import as_compatible_data, as_variable -from xarray.tests import requires_bottleneck - -from . import ( +from xarray.tests import ( assert_allclose, assert_array_equal, assert_equal, @@ -38,6 +36,7 @@ assert_no_warnings, has_pandas_version_two, raise_if_dask_computes, + requires_bottleneck, requires_cupy, requires_dask, requires_pandas_version_two, diff --git a/xarray/tests/test_weighted.py b/xarray/tests/test_weighted.py index 1a739bea001..8083e545962 100644 --- a/xarray/tests/test_weighted.py +++ b/xarray/tests/test_weighted.py @@ -7,9 +7,13 @@ import xarray as xr from xarray import DataArray, Dataset -from xarray.tests import assert_allclose, assert_equal - -from . import raise_if_dask_computes, requires_cftime, requires_dask +from xarray.tests import ( + assert_allclose, + assert_equal, + raise_if_dask_computes, + requires_cftime, + requires_dask, +) @pytest.mark.parametrize("as_dataset", (True, False)) diff --git a/xarray/tutorial.py b/xarray/tutorial.py index d1373633564..fca22aaf5af 100644 --- a/xarray/tutorial.py +++ b/xarray/tutorial.py @@ -14,13 +14,13 @@ import numpy as np -from .backends.api import open_dataset as _open_dataset -from .backends.rasterio_ import open_rasterio as _open_rasterio -from .core.dataarray import DataArray -from .core.dataset import Dataset +from xarray.backends.api import open_dataset as _open_dataset +from xarray.backends.rasterio_ import open_rasterio as _open_rasterio +from xarray.core.dataarray import DataArray +from xarray.core.dataset import Dataset if TYPE_CHECKING: - from .backends.api import T_Engine + from xarray.backends.api import T_Engine _default_cache_dir_name = "xarray_tutorial_data"