Skip to main content

TypedUnit — physical quantities with readable types and runtime checks

Badge

Status

Python versions

Supported Python versions

Documentation

Documentation build

Continuous integration

Test status

Test coverage

Test coverage

PyPI package

PyPI version

PyPI downloads

Monthly PyPI downloads

Anaconda package

Anaconda version

TypedUnit

Physical quantities with readable types and runtime checks.

TypedUnit adds dimensional types such as Length, Energy, and Power to Pint. Keep ordinary Pint quantities, arithmetic, and unit conversions, then add validation where values enter your functions. Catch a distance passed as an energy before a calculation begins.

Documentation | Quick start | Examples | Report an issue

Features

  • Dimensional type checks: isinstance(quantity, Energy) accepts joules, kilowatt hours, and other compatible energy units.

  • Function input validation: @unit_validator checks annotated inputs and reports the parameter that failed. validate_units is an alias.

  • Array contracts: distinguish scalars, vectors, and matrices, with optional fixed sizes such as Vector[3].

  • Value constraints: require floating-point, finite, nonzero, positive, or negative magnitudes directly in annotations.

  • Direct validation: check a quantity’s dimensions, registry, shape, and values without replacing it.

  • Pint interoperability: quantities retain their units, NumPy behavior, and explicit .to(...) conversions.

Installation

Install from PyPI using Python 3.10 or newer:

python -m pip install TypedUnit

Or install from the author’s Conda channel:

conda install --channel martinpdes typedunit

Verify the installation with the interpreter you will use for your code:

python -c "import TypedUnit; print(TypedUnit.__version__)"

The current dependency range is Pint >=0.24,<0.26. NumPy, Matplotlib, and pint-pandas are installed automatically. Pydantic is optional and can be installed separately for model or dataclass integrations.

First calculation

Create values with the shared ureg registry, annotate a function’s inputs, and add @unit_validator:

from TypedUnit import Energy, Power, Time, unit_validator, ureg

@unit_validator
def average_power(*, energy: Energy, duration: Time) -> Power:
    """Calculate average power from energy and elapsed time.

    Parameters
    ----------
    energy : Energy
        Input energy, with units compatible with joules.
    duration : Time
        Elapsed time, with units compatible with seconds; must be nonzero.

    Returns
    -------
    Power
        Average power expressed in watts.
    """
    return (energy / duration).to(ureg.watt)

energy = 100 * ureg.joule

duration = 10 * ureg.second

power = average_power(
    energy=energy,
    duration=duration,
)

print(f"Average power: {power}")

Output:

Average power: 10.0 watt

The inputs remain Pint quantities. The annotation describes their physical meaning; .to(ureg.watt) explicitly selects the output unit.

Catch a dimensional mistake

Using the function above, pass a length where an energy is required:

try:
    average_power(
        energy=5 * ureg.meter,
        duration=duration,
    )
except ValueError as error:
    print(f"Invalid input: {error}")

Output:

Invalid input: Parameter 'energy' must have units compatible with Energy.

Validation runs before the function body. It checks dimensional compatibility, so an energy in kilojoules is valid without an automatic conversion to joules. Use additional constraints when a value must also be finite, nonzero, or positive.

Validate array shapes and values

Combine a physical type with shape and value markers. This function accepts exactly three finite, positive floating-point power samples:

import numpy as np
from TypedUnit import Finite, Float, Positive, Power, Vector, unit_validator, ureg

@unit_validator
def mean_power(*, samples: Power[Vector[3], Float, Finite, Positive]) -> Power:
    """Calculate the mean of three positive power samples.

    Parameters
    ----------
    samples : Power[Vector[3], Float, Finite, Positive]
        Three finite, strictly positive floating-point power values.

    Returns
    -------
    Power
        Mean power expressed in watts.
    """
    return samples.mean().to(ureg.watt)

samples = np.array([1.0, 2.0, 3.0]) * ureg.milliwatt

power = mean_power(samples=samples)

print(f"Mean power: {power}")

Output:

Mean power: 0.002 watt

Scalar requires a zero-dimensional magnitude, Vector a one-dimensional magnitude, and Matrix a two-dimensional magnitude. Use Vector[n] or Matrix[rows, columns] for exact sizes. Constraints apply to every magnitude; Float requires floating-point values rather than converting integers.

See the validation guide for optional inputs, collections, sign unions, and additional examples.

Validate a quantity directly

Use validate_quantity when you need an explicit validation step instead of a decorated function:

from TypedUnit import ureg, validate_quantity

wavelength = 850 * ureg.nanometer

validate_quantity(
    value=wavelength,
    unit="m",
    name="wavelength",
    registry=ureg,
    shape=(),
    positive=True,
)

print(f"Validated wavelength: {wavelength}")

Output:

Validated wavelength: 850 nanometer

The function returns None and leaves the original quantity and its units unchanged. Here it requires a finite, positive scalar length from ureg. Omit registry to accept quantities from any Pint registry; omit shape to leave the shape unrestricted. Nonfinite values are rejected by default.

Physical types and conventions

Some of the available dimensional types are:

Domain

Types

Energy and time

Energy, Power (also Watt), Time, Frequency

Space and motion

Length, Area, Volume, Velocity, Angle

Electrical

Voltage, Current, Resistance, Ohm

Matter and flow

Mass, Concentration, FlowRate, Viscosity, Temperature

Optical and dimensionless

ElectricField, RefractiveIndex, Dimensionless

Types describe dimensionality rather than a specific display unit. Construct values with 3 * ureg.joule, rather than calling Energy(...). You can also compose dimensional types:

from TypedUnit import Energy, Time, ureg

EnergyPerTime = Energy / Time

power = 2 * ureg.watt

print(f"Has power dimensions: {isinstance(power, EnergyPerTime)}")

Output:

Has power dimensions: True

Use Dimensionless for dimensionless Pint quantities. Use NoUnit when an input must be a bare number and Pint quantities must be rejected, including dimensionless quantities. For example, NoUnit[Scalar, Float, Positive] describes a bare positive floating-point scalar.

The unit reference lists the available types.

Common issues

  • An annotation alone does not validate a function. Add @unit_validator to check supported input annotations at call time. Ordinary str and int annotations and return values are not runtime-validated.

  • Runtime checks are distinct from static analysis. Dimensional markers and shape annotations do not provide static unit or shape inference.

  • Compatible dimensions do not imply the same physical meaning. Checks cannot distinguish quantities that share dimensions, such as frequency and angular frequency. Keep conventions explicit in your API.

  • Keep registry ownership consistent. Prefer TypedUnit.ureg throughout an application. Quantities from different Pint registries can fail when combined, even if their dimensions match.

  • A one-element array is not a scalar. Scalar requires shape (); an array with shape (1,) is a vector.

  • A bare number has no physical units. Attach units to dimensional inputs, or use NoUnit for deliberately unitless inputs.

Read the Pint integration guide for registry and conversion conventions.

Developer setup

Clone the repository and install it into a virtual environment:

git clone https://github.com/MartinPdeS/TypedUnit.git
cd TypedUnit
python -m venv .venv
source .venv/bin/activate
python -m pip install -e ".[testing,documentation,dev]"

On Windows, activate the environment with .venv\Scripts\activate instead. Run tests, lint checks, and the documentation build with the same interpreter:

python -m pytest
python -m ruff check TypedUnit tests
python -m sphinx -b html docs/source docs/build/html

See CONTRIBUTING.md for contribution and release guidance.

Contact and license

Questions, bug reports, and proposed improvements are welcome on the issue tracker. For other inquiries, contact Martin Poinsinet de Sivry-Houle.

TypedUnit is distributed under the MIT license.

Metadata

Release files for TypedUnit 0.6.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 TypedUnit 0.6.0
File Size Uploaded Provenance Actions
typedunit-0.6.0.tar.gz 25.5 kB Without provenance Details for typedunit-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for TypedUnit 0.6.0
File Interpreter ABI Platform Actions
typedunit-0.6.0-py3-none-any.whl Python 3 none any Details for typedunit-0.6.0-py3-none-any.whl

Total release size: 43.2 kB

Release files / typedunit-0.6.0.tar.gz

Download URL typedunit-0.6.0.tar.gz
Size 25.5 kB
Tags Source
SHA-256 checksum
How to use checksums
94cd72394c978f32522b9eab68a19b3c1e5941d76508a3658fb4218561503f53
BLAKE2b-256 checksum
How to use checksums
768a95419587f977fd8266e49afb3b8ed7abc259b692bbec42a474253ec666f1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.18

Release files / typedunit-0.6.0-py3-none-any.whl

Download URL typedunit-0.6.0-py3-none-any.whl
Size 17.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
18aacba1beb75eb7994a797666fbcac87bb694cdb3b0d0b3137d60b5184594e0
BLAKE2b-256 checksum
How to use checksums
f89dd8163efea028aa0f31c291fc57d220100bf468aa28892442b5d34075dd85
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.18

Security for TypedUnit 0.6.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