|
| 1 | +__all__ = ["Attr", "Coord", "Data", "Multiple", "Tag"] |
| 2 | + |
| 3 | + |
| 4 | +# standard library |
| 5 | +from collections.abc import Collection |
| 6 | +from dataclasses import Field |
| 7 | +from enum import auto |
| 8 | +from typing import Annotated as Ann, Any, Callable, ClassVar, Protocol, TypeVar, Union |
| 9 | + |
| 10 | + |
| 11 | +# dependencies |
| 12 | +from dataspecs import TagBase |
| 13 | +from typing_extensions import ParamSpec |
| 14 | +from xarray import DataArray, Dataset |
| 15 | + |
| 16 | + |
| 17 | +# type hints |
| 18 | +P = ParamSpec("P") |
| 19 | +TAny = TypeVar("TAny") |
| 20 | +TArray = TypeVar("TArray", bound=DataArray) |
| 21 | +TDims = TypeVar("TDims", covariant=True) |
| 22 | +TDtype = TypeVar("TDtype", covariant=True) |
| 23 | +TSet = TypeVar("TSet", bound=Dataset) |
| 24 | +TXarray = TypeVar("TXarray", bound=Union[DataArray, Dataset]) |
| 25 | + |
| 26 | + |
| 27 | +class DataClass(Protocol[P]): |
| 28 | + """Protocol for dataclass (object).""" |
| 29 | + |
| 30 | + __dataclass_fields__: ClassVar[dict[str, Field[Any]]] |
| 31 | + |
| 32 | + def __init__(self, *args: P.args, **kwargs: P.kwargs) -> None: ... |
| 33 | + |
| 34 | + |
| 35 | +class DataClassOf(Protocol[TXarray, P]): |
| 36 | + """Protocol for dataclass (object) with an xarray factory.""" |
| 37 | + |
| 38 | + __dataclass_fields__: ClassVar[dict[str, Field[Any]]] |
| 39 | + __xarray_factory__: Callable[..., TXarray] |
| 40 | + |
| 41 | + def __init__(self, *args: P.args, **kwargs: P.kwargs) -> None: ... |
| 42 | + |
| 43 | + |
| 44 | +class Labeled(Collection[TDtype], Protocol[TDims, TDtype]): |
| 45 | + """Same as Collection but accepts additional type variable for dims.""" |
| 46 | + |
| 47 | + pass |
| 48 | + |
| 49 | + |
| 50 | +# constants |
| 51 | +class Tag(TagBase): |
| 52 | + """Collection of xarray-related tags for annotating type hints.""" |
| 53 | + |
| 54 | + ATTR = auto() |
| 55 | + """Tag for specifying an attribute of DataArray/set.""" |
| 56 | + |
| 57 | + COORD = auto() |
| 58 | + """Tag for specifying a coordinate of DataArray/set.""" |
| 59 | + |
| 60 | + DATA = auto() |
| 61 | + """Tag for specifying a data object of DataArray/set.""" |
| 62 | + |
| 63 | + DIMS = auto() |
| 64 | + """Tag for specifying a dims object of DataArray/set.""" |
| 65 | + |
| 66 | + DTYPE = auto() |
| 67 | + """Tag for specifying a dtype object of DataArray/set.""" |
| 68 | + |
| 69 | + MULTIPLE = auto() |
| 70 | + """Tag for specifying multiple items of DataArray/set.""" |
| 71 | + |
| 72 | + |
| 73 | +# type aliases |
| 74 | +Attr = Ann[TAny, Tag.ATTR] |
| 75 | +Coord = Ann[Labeled[Ann[TDims, Tag.DIMS], Ann[TDtype, Tag.DTYPE]], Tag.COORD] |
| 76 | +Data = Ann[Labeled[Ann[TDims, Tag.DIMS], Ann[TDtype, Tag.DTYPE]], Tag.DATA] |
| 77 | +Multiple = dict[str, Ann[TAny, Tag.MULTIPLE]] |
0 commit comments