Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Buffer types #9787

Merged
merged 3 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions xarray/backends/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@
from dask.delayed import Delayed
except ImportError:
Delayed = None # type: ignore[assignment, misc]
from io import BufferedIOBase

from xarray.backends.common import BackendEntrypoint
from xarray.core.types import (
CombineAttrsOptions,
CompatOptions,
JoinOptions,
NestedSequence,
ReadBuffer,
T_Chunks,
)

Expand Down Expand Up @@ -474,7 +474,7 @@ def _datatree_from_backend_datatree(


def open_dataset(
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
engine: T_Engine = None,
chunks: T_Chunks = None,
Expand Down Expand Up @@ -691,7 +691,7 @@ def open_dataset(


def open_dataarray(
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
engine: T_Engine | None = None,
chunks: T_Chunks | None = None,
Expand Down Expand Up @@ -896,7 +896,7 @@ def open_dataarray(


def open_datatree(
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
engine: T_Engine = None,
chunks: T_Chunks = None,
Expand Down Expand Up @@ -1111,7 +1111,7 @@ def open_datatree(


def open_groups(
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
engine: T_Engine = None,
chunks: T_Chunks = None,
Expand All @@ -1137,10 +1137,6 @@ def open_groups(
and cannot be opened directly with ``open_datatree``. It is encouraged to use this function to inspect your data,
then make the necessary changes to make the structure coercible to a `DataTree` object before calling `DataTree.from_dict()` and proceeding with your analysis.

Parameters
----------
filename_or_obj : str, Path, file-like, or DataStore
Strings and Path objects are interpreted as a path to a netCDF file.
Parameters
----------
filename_or_obj : str, Path, file-like, or DataStore
Expand Down Expand Up @@ -1338,7 +1334,10 @@ def open_groups(


def open_mfdataset(
paths: str | os.PathLike | NestedSequence[str | os.PathLike],
paths: str
| os.PathLike
| ReadBuffer
| NestedSequence[str | os.PathLike | ReadBuffer],
chunks: T_Chunks | None = None,
concat_dim: (
str
Expand Down Expand Up @@ -1541,7 +1540,7 @@ def open_mfdataset(
if not paths:
raise OSError("no files to open")

paths1d: list[str]
paths1d: list[str | ReadBuffer]
if combine == "nested":
if isinstance(concat_dim, str | DataArray) or concat_dim is None:
concat_dim = [concat_dim] # type: ignore[assignment]
Expand Down
62 changes: 46 additions & 16 deletions xarray/backends/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@
import traceback
from collections.abc import Iterable, Mapping, Sequence
from glob import glob
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast, overload
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, overload

import numpy as np

from xarray.conventions import cf_encoder
from xarray.core import indexing
from xarray.core.datatree import DataTree
from xarray.core.types import ReadBuffer
from xarray.core.utils import FrozenDict, NdimSizeLenMixin, is_remote_uri
from xarray.namedarray.parallelcompat import get_chunked_array_type
from xarray.namedarray.pycompat import is_chunked_array

if TYPE_CHECKING:
from io import BufferedIOBase

from xarray.core.dataset import Dataset
from xarray.core.types import NestedSequence

Expand Down Expand Up @@ -65,24 +64,52 @@ def _normalize_path(path: str | os.PathLike | T) -> str | T:
if isinstance(path, str) and not is_remote_uri(path):
path = os.path.abspath(os.path.expanduser(path))

return cast(str, path)
return path # type:ignore [return-value]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does mypy complain here? Shouldn't it take the T path here?



@overload
def _find_absolute_paths(
paths: str | os.PathLike | Sequence[str | os.PathLike], **kwargs
paths: str | os.PathLike | Sequence[str | os.PathLike],
**kwargs,
) -> list[str]: ...


@overload
def _find_absolute_paths(
paths: ReadBuffer | Sequence[ReadBuffer],
**kwargs,
) -> list[ReadBuffer]: ...


@overload
def _find_absolute_paths(
paths: NestedSequence[str | os.PathLike], **kwargs
) -> NestedSequence[str]: ...


@overload
def _find_absolute_paths(
paths: str | os.PathLike | NestedSequence[str | os.PathLike], **kwargs
) -> NestedSequence[str]:
paths: NestedSequence[ReadBuffer], **kwargs
) -> NestedSequence[ReadBuffer]: ...


@overload
def _find_absolute_paths(
paths: str
| os.PathLike
| ReadBuffer
| NestedSequence[str | os.PathLike | ReadBuffer],
**kwargs,
) -> NestedSequence[str | ReadBuffer]: ...


def _find_absolute_paths(
paths: str
| os.PathLike
| ReadBuffer
| NestedSequence[str | os.PathLike | ReadBuffer],
**kwargs,
) -> NestedSequence[str | ReadBuffer]:
"""
Find absolute paths from the pattern.

Expand Down Expand Up @@ -132,10 +159,12 @@ def _find_absolute_paths(
return sorted(glob(_normalize_path(paths)))
elif isinstance(paths, os.PathLike):
return [_normalize_path(paths)]
elif isinstance(paths, ReadBuffer):
return [paths]

def _normalize_path_list(
lpaths: NestedSequence[str | os.PathLike],
) -> NestedSequence[str]:
lpaths: NestedSequence[str | os.PathLike | ReadBuffer],
) -> NestedSequence[str | ReadBuffer]:
paths = []
for p in lpaths:
if isinstance(p, str | os.PathLike):
Expand Down Expand Up @@ -546,10 +575,9 @@ def __repr__(self) -> str:

def open_dataset(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
drop_variables: str | Iterable[str] | None = None,
**kwargs: Any,
) -> Dataset:
"""
Backend open_dataset method used by Xarray in :py:func:`~xarray.open_dataset`.
Expand All @@ -559,7 +587,7 @@ def open_dataset(

def guess_can_open(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
) -> bool:
"""
Backend open_dataset method used by Xarray in :py:func:`~xarray.open_dataset`.
Expand All @@ -569,8 +597,9 @@ def guess_can_open(

def open_datatree(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
**kwargs: Any,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
drop_variables: str | Iterable[str] | None = None,
) -> DataTree:
"""
Backend open_datatree method used by Xarray in :py:func:`~xarray.open_datatree`.
Expand All @@ -580,8 +609,9 @@ def open_datatree(

def open_groups_as_dict(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
**kwargs: Any,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
drop_variables: str | Iterable[str] | None = None,
) -> dict[str, Dataset]:
"""
Opens a dictionary mapping from group names to Datasets.
Expand Down
13 changes: 6 additions & 7 deletions xarray/backends/h5netcdf_.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,10 @@
from xarray.core.variable import Variable

if TYPE_CHECKING:
from io import BufferedIOBase

from xarray.backends.common import AbstractDataStore
from xarray.core.dataset import Dataset
from xarray.core.datatree import DataTree
from xarray.core.types import ReadBuffer


class H5NetCDFArrayWrapper(BaseNetCDF4Array):
Expand Down Expand Up @@ -395,7 +394,7 @@ class H5netcdfBackendEntrypoint(BackendEntrypoint):

def guess_can_open(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
) -> bool:
magic_number = try_read_magic_number_from_file_or_path(filename_or_obj)
if magic_number is not None:
Expand All @@ -407,9 +406,9 @@ def guess_can_open(

return False

def open_dataset( # type: ignore[override] # allow LSP violation, not supporting **kwargs
def open_dataset(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
mask_and_scale=True,
decode_times=True,
Expand Down Expand Up @@ -456,7 +455,7 @@ def open_dataset( # type: ignore[override] # allow LSP violation, not supporti

def open_datatree(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
mask_and_scale=True,
decode_times=True,
Expand Down Expand Up @@ -499,7 +498,7 @@ def open_datatree(

def open_groups_as_dict(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
mask_and_scale=True,
decode_times=True,
Expand Down
13 changes: 6 additions & 7 deletions xarray/backends/netCDF4_.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,13 @@
from xarray.core.variable import Variable

if TYPE_CHECKING:
from io import BufferedIOBase

from h5netcdf.core import EnumType as h5EnumType
from netCDF4 import EnumType as ncEnumType

from xarray.backends.common import AbstractDataStore
from xarray.core.dataset import Dataset
from xarray.core.datatree import DataTree
from xarray.core.types import ReadBuffer

# This lookup table maps from dtype.byteorder to a readable endian
# string used by netCDF4.
Expand Down Expand Up @@ -627,7 +626,7 @@ class NetCDF4BackendEntrypoint(BackendEntrypoint):

def guess_can_open(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
) -> bool:
if isinstance(filename_or_obj, str) and is_remote_uri(filename_or_obj):
return True
Expand All @@ -642,9 +641,9 @@ def guess_can_open(

return False

def open_dataset( # type: ignore[override] # allow LSP violation, not supporting **kwargs
def open_dataset(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
mask_and_scale=True,
decode_times=True,
Expand Down Expand Up @@ -693,7 +692,7 @@ def open_dataset( # type: ignore[override] # allow LSP violation, not supporti

def open_datatree(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
mask_and_scale=True,
decode_times=True,
Expand Down Expand Up @@ -735,7 +734,7 @@ def open_datatree(

def open_groups_as_dict(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
mask_and_scale=True,
decode_times=True,
Expand Down
4 changes: 2 additions & 2 deletions xarray/backends/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
if TYPE_CHECKING:
import os
from importlib.metadata import EntryPoint, EntryPoints
from io import BufferedIOBase

from xarray.backends.common import AbstractDataStore
from xarray.core.types import ReadBuffer

STANDARD_BACKENDS_ORDER = ["netcdf4", "h5netcdf", "scipy"]

Expand Down Expand Up @@ -138,7 +138,7 @@ def refresh_engines() -> None:


def guess_engine(
store_spec: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
store_spec: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
) -> str | type[BackendEntrypoint]:
engines = list_engines()

Expand Down
8 changes: 4 additions & 4 deletions xarray/backends/pydap_.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@

if TYPE_CHECKING:
import os
from io import BufferedIOBase

from xarray.core.dataset import Dataset
from xarray.core.types import ReadBuffer


class PydapArrayWrapper(BackendArray):
Expand Down Expand Up @@ -166,13 +166,13 @@ class PydapBackendEntrypoint(BackendEntrypoint):

def guess_can_open(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
) -> bool:
return isinstance(filename_or_obj, str) and is_remote_uri(filename_or_obj)

def open_dataset( # type: ignore[override] # allow LSP violation, not supporting **kwargs
def open_dataset(
self,
filename_or_obj: str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore,
filename_or_obj: str | os.PathLike[Any] | ReadBuffer | AbstractDataStore,
*,
mask_and_scale=True,
decode_times=True,
Expand Down
Loading
Loading