First principles¶
Writing a declaration¶
A declaration is one or more markers in an Annotated hint on a parameter or return value.
Decorate the function with enforce and the markers are checked on every call:
from typing import Annotated
import xarray as xr
import xarray_annotated as xra
from xarray_annotated import Dims, Unit
@xra.enforce
def mean_over_time(
x: Annotated[xr.DataArray, Dims("time", "site"), Unit("K")],
) -> Annotated[xr.DataArray, Dims("site"), Unit("K")]:
return x.mean("time")
| Marker | Passes when | More |
|---|---|---|
Dims("time", "x") |
The array has exactly these dims, in any order | Schema |
Coords("time") |
These coordinates are present, and extras are fine | Schema |
Dtype("float64") |
The array has this dtype, and Dtype("float") means any float |
Schema |
Unit("hPa") |
The array is in this unit, however it is spelled | Units |
Freq("h") |
The time axis has this spacing | Temporal |
Declare as much or as little as you like: a marker you leave off is not checked, and neither is a parameter with no markers, so you can adopt this one function at a time.
How checks behave¶
- Declarations are checked at decoration: a malformed declaration, such as a misspelled unit, raises
ValueErrorwhen the module is imported. - Arrays are checked on each call: inputs before the body, and outputs after it.
- Each array stops at its first failure: units are checked first, then structure, then frequency.
- Every failed check raises: a
ContractErrorand not aValueError, asUnitError,SchemaErrorandFreqErrorare. There are no warnings and no lenient mode. - Only a
DataArraypasses: anything else raisesContractError, includingNone, unless the hint allows it. - Only metadata is read: names, dtypes, unit labels and indexes, never values, so a lazily opened array stays unread. A check therefore cannot tell whether a label is true.
- Checks change nothing: the body receives the arrays the caller passed, and the caller receives what the body returned, with no conversion or relabelling.
- Only markers declare anything: anything else in the hint is ignored, so
Annotated[xr.DataArray, "Pa"]checks nothing.
Multiple returns¶
Return a TypedDict or dataclass, and declare its fields:
from typing import NotRequired, TypedDict
import numpy as np
class Wind(TypedDict):
speed: Annotated[xr.DataArray, Dims("time"), Unit("m/s")]
direction: Annotated[xr.DataArray, Dims("time"), Unit("degree")]
gust: NotRequired[Annotated[xr.DataArray, Dims("time"), Unit("m/s")]]
@xra.enforce
def wind(
u: Annotated[xr.DataArray, Dims("time"), Unit("m/s")],
v: Annotated[xr.DataArray, Dims("time"), Unit("m/s")],
) -> Wind:
speed = np.hypot(u, v).assign_attrs(units="m/s")
direction = np.degrees(np.arctan2(u, v)).assign_attrs(units="degree")
return {"speed": speed, "direction": direction}
from dataclasses import dataclass
import numpy as np
@dataclass
class Wind:
speed: Annotated[xr.DataArray, Dims("time"), Unit("m/s")]
direction: Annotated[xr.DataArray, Dims("time"), Unit("degree")]
gust: Annotated[xr.DataArray, Dims("time"), Unit("m/s")] | None = None
@xra.enforce
def wind(
u: Annotated[xr.DataArray, Dims("time"), Unit("m/s")],
v: Annotated[xr.DataArray, Dims("time"), Unit("m/s")],
) -> Wind:
speed = np.hypot(u, v).assign_attrs(units="m/s")
direction = np.degrees(np.arctan2(u, v)).assign_attrs(units="degree")
return Wind(speed=speed, direction=direction)
- Missing fields: leaving out a required field raises
ContractError, whereas aNotRequiredfield may be absent, and a dataclass field declared| Nonemay beNone. - Undeclared fields: a field with no markers is not checked.
- The container itself: the caller receives a shallow copy of the dict or dataclass, which shares its arrays, and
__post_init__does not run again.
A tuple or NamedTuple return has no fields enforce can read, so markers there raise ValueError when the function is decorated.
The same goes for a parameter holding a class with declared fields, so declare a parameter’s arrays as parameters of their own.
Optional arguments and Unions¶
Add what else a value may be to the hint as a union, on a parameter, a return value or a field of a returned class.
Markers are checked only when the value is a DataArray.
With A standing for Annotated[xr.DataArray, Unit("K")]:
| Hint | DataArray |
None |
Anything else |
|---|---|---|---|
A |
checked | ContractError |
ContractError |
A | None |
checked | passes | ContractError |
A | float |
checked | ContractError |
passes |
A | float | None |
checked | passes | passes |
- A default is not enough: defaults are checked too, so
x: A = NoneraisesContractErrorwhenxis left out; writex: A | None = None. - Other types are not checked:
A | floataccepts a string, just asn: intdoes, so leave those to a type checker. - The union goes outside the
Annotated:Annotated[xr.DataArray | None, Unit("K")]andAnnotated[xr.DataArray | float, Unit("K")]raiseValueErrorwhen the function is decorated. - Only one member can be declared:
A | list[A]and a union of two declared arrays raiseValueErrorwhen the function is decorated. - A returned class can only be optional:
Wind | Noneis fine, and any other union holding it raisesValueErrorwhen the function is decorated.
Switching the package off¶
While prototyping, switch the package off:
Off is a total no-op, so a function declaring Unit("Pa") can receive hPa.
Malformed declarations still raise when a function is decorated.
- For a process: set
XARRAY_ANNOTATED_ENABLEDto0,false,nooroff. - Precedence: a block beats the variable in both directions, and the innermost block wins.
- Scope: a block applies to the current thread or async task only, and to dask’s threaded and synchronous schedulers when it surrounds
.compute(). It does not reach a new thread or another process.