Skip to main content

xarray-annotated

PyPI version Python versions CI Docs License: MIT

xarray-annotated checks xarray.DataArray arguments and return values against properties declared in the function signature with typing.Annotated:

  • structure: dimensions, coordinates and dtype;
  • physical units;
  • time frequency and phase.

Making signatures the single source of truth has several advantages: the same declaration

  • can be used by automated checks and validation, and hence enforced at run time;
  • appears in generated documentation without needing to be hand-written;
  • provides rich context for AI coding agents.

For physical units we lean on the excellent pint and pint-xarray. (cf-xarray is an optional dependency for CF/UDUNITS unit strings.)

For full user documentation please visit https://jmarshrossney.github.io/xarray-annotated/.

Installation

Either using uv (recommended) or pip:

uv add xarray-annotated
# or
pip install xarray-annotated

CF-convention / UDUNITS unit strings (e.g. "umol m-2 s-1") need the optional cf extra, which pulls in cf-xarray.

uv add "xarray-annotated[cf]"
# or
pip install "xarray-annotated[cf]"

A short example

Here is a function that converts barometric pressure to altitude. It assumes a unit (pascals) and says so in the docstring but doesn't check or enforce it.

import xarray as xr


def altitude(p: xr.DataArray) -> xr.DataArray:
    """Barometric altitude. Assumes p is in Pa."""
    return 44330.0 * (1.0 - (p / 101325.0) ** 0.1903)


p = xr.DataArray([1013.0, 1000.0], dims=["time"], attrs={"units": "hPa"})
altitude(p)
<xarray.DataArray (time: 2)> Size: 16B
array([25876.55998663, 25921.86206292])
Dimensions without coordinates: time
Attributes:
    units:    hPa

The input units are wrong (hPa vs Pa) but the onus is on the user to check, and in reality we all know that such bugs can go unnoticed for a terrifyingly long time. The returned altitude is numerically wrong and carries a completely bogus hPa units in attrs.

Here we use xarray-annotated to declare expected properties in the signature and enforce them at run-time with minimal boilerplate (one decorator).

from typing import Annotated
import xarray as xr
import xarray_annotated as xra
from xarray_annotated import Dims, Unit


@xra.enforce
def altitude(
    p: Annotated[xr.DataArray, Dims("time"), Unit("Pa")],
) -> Annotated[xr.DataArray, Dims("time"), Unit("m")]:
    """Barometric altitude."""
    alt = 44330.0 * (1.0 - (p / 101325.0) ** 0.1903)
    return alt.assign_attrs(units="m")


p = xr.DataArray([1013.0, 1000.0], dims=["time"], attrs={"units": "hPa"})
altitude(p)
# ValueError: [altitude] input 'p': unit 'hPa' differs from declared 'Pa'.
#   Converting would change the values; if that is correct for this quantity,
#   pass xra.units.convert(da, 'Pa').

The wrong unit is now an error rather than a wrong answer. Pressure is safe to convert, so we can do that explicitly:

altitude(xra.units.convert(p, "Pa"))
<xarray.DataArray (time: 2)> Size: 16B
array([  2.08162886, 110.90398059])
Dimensions without coordinates: time
Attributes:
    units:    m

Now the outputs are physical and carry the unit the signature promised. The body has to state that unit, because xarray would otherwise leave the Pa label on the result, and a label that disagrees with the declaration raises: it could just as easily mean a forgotten conversion. Nothing is converted automatically, because whether a conversion is correct depends on the quantity, and a compatible unit is not always the right one. The docstring no longer needs to say "assumes Pa", because the signature does --- and unlike the docstring, it is actually enforced.

An array whose units were dimensionally wrong would also have raised:

altitude(xr.DataArray([1.0, 2.0], dims=["time"], attrs={"units": "kg"}))
# DimensionalityError: Cannot convert from 'kilogram' ([mass])
#   to 'pascal' ([mass] / [length] / [time] ** 2)

And so would one with an extra dimension:

altitude(
    xr.DataArray([[101300.0, 100000.0]], dims=["run", "time"], attrs={"units": "Pa"})
)
# SchemaError: [altitude] 'p' dims mismatch: expected ('time',) in any order, got ('run', 'time')

Contributing

Issues and pull requests are welcome. See CONTRIBUTING.md for the package's scope and how to set up a development environment.

Metadata

Release files for xarray-annotated 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xarray-annotated 0.7.0
File Size Uploaded Provenance Actions
xarray_annotated-0.7.0.tar.gz 36.0 kB Without provenance Details for xarray_annotated-0.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xarray-annotated 0.7.0
File Interpreter ABI Platform Actions
xarray_annotated-0.7.0-py3-none-any.whl Python 3 none any Details for xarray_annotated-0.7.0-py3-none-any.whl

Total release size: 79.5 kB

Release files / xarray_annotated-0.7.0.tar.gz

Download URL xarray_annotated-0.7.0.tar.gz
Size 36.0 kB
Tags Source
SHA-256 checksum
How to use checksums
65b7912e0917e425553055542a5ec73c669430cec04503059f655a507b83d1e1
BLAKE2b-256 checksum
How to use checksums
b346341eb4d1cb0a3ee671feb8423218cc4ff2143d8b8cf2f9024c43931585ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / xarray_annotated-0.7.0-py3-none-any.whl

Download URL xarray_annotated-0.7.0-py3-none-any.whl
Size 43.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dcce9af3149aaeb571966862b7e55bb245c82ee36deb86159c8a6c989ab81cc4
BLAKE2b-256 checksum
How to use checksums
1551ec438cfc5a1a860fbb250da88e736cedd50334097b5d2cb4eddf01c07adc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for xarray-annotated 0.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page