xarray_dataclasses.typing module#
Submodule for type hints to define fields of dataclasses.
Note
The following code is supposed in the examples below:
from dataclasses import dataclass
from typing import Literal
from xarray_dataclasses import AsDataArray, AsDataset
from xarray_dataclasses import Attr, Coord, Data, Name
from xarray_dataclasses import Coordof, Dataof
X = Literal["x"]
Y = Literal["y"]
- Attr#
Type hint for attribute fields (
Attr[T]
).Example
@dataclass class Image(AsDataArray): data: Data[tuple[X, Y], float] long_name: Attr[str] = "luminance" units: Attr[str] = "cd / m^2"
Hint
The following field names are specially treated when plotting.
long_name
orstandard_name
: Coordinate name.units
: Coordinate units.
alias of
Annotated
[T
]
- Coord#
Type hint for coordinate fields (
Coord[TDims, TDType]
).Example
@dataclass class Image(AsDataArray): data: Data[tuple[X, Y], float] mask: Coord[tuple[X, Y], bool] x: Coord[X, int] = 0 y: Coord[Y, int] = 0
Hint
A coordinate field whose name is the same as
TDims
(e.g.x: Coord[X, int]
) can define a dimension.alias of
Annotated
[Union
[Labeled
[TDims
],Collection
[TDType
],TDType
]]
- Coordof#
Type hint for coordinate fields (
Coordof[TDataClass]
).Unlike
Coord
, it specifies a dataclass that defines a DataArray class. This is useful when users want to add metadata to dimensions for plotting.Example
@dataclass class XAxis: data: Data[X, int] long_name: Attr[str] = "x axis" @dataclass class YAxis: data: Data[Y, int] long_name: Attr[str] = "y axis" @dataclass class Image(AsDataArray): data: Data[tuple[X, Y], float] x: Coordof[XAxis] = 0 y: Coordof[YAxis] = 0
Hint
A class used in
Coordof
does not need to inheritAsDataArray
.alias of
Annotated
[Union
[TDataClass
,Any
]]
- Data#
Type hint for data fields (
Coordof[TDims, TDType]
).Example
Exactly one data field is allowed in a DataArray class (the second and subsequent data fields are just ignored):
@dataclass class Image(AsDataArray): data: Data[tuple[X, Y], float]
Multiple data fields are allowed in a Dataset class:
@dataclass class ColorImage(AsDataset): red: Data[tuple[X, Y], float] green: Data[tuple[X, Y], float] blue: Data[tuple[X, Y], float]
alias of
Annotated
[Union
[Labeled
[TDims
],Collection
[TDType
],TDType
]]
- Dataof#
Type hint for data fields (
Coordof[TDataClass]
).Unlike
Data
, it specifies a dataclass that defines a DataArray class. This is useful when users want to reuse a dataclass in a Dataset class.Example
@dataclass class Image: data: Data[tuple[X, Y], float] x: Coord[X, int] = 0 y: Coord[Y, int] = 0 @dataclass class ColorImage(AsDataset): red: Dataof[Image] green: Dataof[Image] blue: Dataof[Image]
Hint
A class used in
Dataof
does not need to inheritAsDataArray
.alias of
Annotated
[Union
[TDataClass
,Any
]]
- Name#
Type hint for name fields (
Name[THashable]
).Example
@dataclass class Image(AsDataArray): data: Data[tuple[X, Y], float] name: Name[str] = "image"
alias of
Annotated
[THashable
]