Badge |
Status |
|---|---|
Python versions |
|
Documentation |
|
Continuous integration |
|
Test coverage |
|
PyPI package |
|
PyPI downloads |
|
Anaconda package |
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.5.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| typedunit-0.5.1.tar.gz | 25.4 kB | Without provenance | Details for typedunit-0.5.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| typedunit-0.5.1-py3-none-any.whl | Python 3 | none | any | Details for typedunit-0.5.1-py3-none-any.whl |
Total release size: 43.0 kB
Release files / typedunit-0.5.1.tar.gz
| Download URL | typedunit-0.5.1.tar.gz |
|---|---|
| Size | 25.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
eabb5515617be6772d40a74f7ecdd346e8b38dcb5dd12010f9b16f7f419adcc9
|
|
BLAKE2b-256 checksum How to use checksums |
a7cad326b8c9c34f8c48b6c697c2ca305ab9ae45c87caeae99ae24a908e0fcd5
|
| 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.5.1-py3-none-any.whl
| Download URL | typedunit-0.5.1-py3-none-any.whl |
|---|---|
| Size | 17.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
af255df9b8405fba99f6d8f09c1b14dd95599aed4b358ae786dfa00634a1cc81
|
|
BLAKE2b-256 checksum How to use checksums |
2d005c5e38dbe03d6deab4b4130f52f93eaf89aca0cf5b38a64a35679cc0a691
|
| 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.5.1
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.