Skip to main content

TypedUnit

TypedUnit logo

Badge

Status

Python versions

Python version

Documentation

Documentation Status

Continuous integration

Continuous integration status

Test coverage

Unittest coverage

PyPI package

PyPI

PyPI downloads

PyPI download statistics

Anaconda package

Anaconda package

Type-safe physical units for Python

TypedUnit is a Python library that extends Pint with type safety and validation capabilities. It allows you to create unit-aware types that work seamlessly with Python’s type system and provide runtime validation for physical quantities.

Key Features:

  • Type Safety: Use isinstance() checks with unit types like Energy, Time, Power

  • Automatic Validation: Function decorators validate units and optional array-shape annotations

  • Pydantic Integration: Full compatibility with Pydantic dataclasses and models

  • Normal Pint Usage: Keep your existing Pint code - just add type safety on top


Quick Example

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

# Normal Pint instantiation
energy = 100 * ureg.joule
time = 10 * ureg.second

# But now isinstance works!
assert isinstance(energy, Energy)  # True
assert isinstance(time, Time)      # True

@unit_validator
def calculate_power(energy: Energy, time: Time) -> Power:
    """Function with automatic unit validation."""
    return (energy / time).to(ureg.watt)

# This works
power = calculate_power(energy, time)
print(f"Power: {power}")

# This fails with clear error message
length = 5 * ureg.meter
# calculate_power(length, time)  # TypeError: Expected Energy, got Length

Installation

pip install TypedUnit

Basic Usage

Unit Type Checking

from TypedUnit import Energy, Length, Mass, ureg

# Create quantities the normal way
kinetic_energy = 0.5 * 10 * ureg.kilogram * (5 * ureg.meter / ureg.second)**2
potential_energy = 10 * ureg.kilogram * 9.81 * ureg.meter / ureg.second**2 * 2 * ureg.meter
distance = 100 * ureg.meter
mass = 5 * ureg.kilogram

# Type checking works
assert isinstance(kinetic_energy, Energy)
assert isinstance(potential_energy, Energy)
assert isinstance(distance, Length)
assert isinstance(mass, Mass)

Function Validation

from TypedUnit import validate_units, Energy, Time, Power

@validate_units
def calculate_work(power: Power, time: Time) -> Energy:
    """Calculate work from power and time."""
    return (power * time).to(ureg.joule)

power = 1500 * ureg.watt
time = 3600 * ureg.second  # 1 hour
work = calculate_work(power, time)
print(f"Work done: {work.to(ureg.kilowatt_hour)}")

Pydantic Integration

from TypedUnit import Energy, Length, Mass
from pydantic.dataclasses import dataclass

@dataclass
class Projectile:
   kinetic_energy: Energy
   height: Length
   mass: Mass

# Automatic validation on creation
projectile = Projectile(
   kinetic_energy=500 * ureg.joule,
   height=10 * ureg.meter,
   mass=2 * ureg.kilogram
)

Available Unit Types

TypedUnit includes common physical unit types:

  • Mechanical: Energy, Power, Force, Pressure

  • Spatial: Length, Area, Volume, Angle

  • Temporal: Time, Frequency

  • Thermal: Temperature, ThermalConductivity

  • Electrical: Current, Voltage, Resistance, Capacitance

  • Optical: RefractiveIndex, Wavelength, ElectricField

  • Mass: Mass, Density, MolarMass


Advanced Features

Custom Unit Types

from TypedUnit import create_unit_type

# Create your own unit types
MagneticField = create_unit_type('MagneticField', '[magnetic_flux_density]')

field = 1.5 * ureg.tesla
assert isinstance(field, MagneticField)

Flexible Validation

from TypedUnit import validate_enhanced

@validate_enhanced(strict_mode=False, convert_types=True)
def flexible_function(energy: Energy, count: int) -> str:
    """Function with flexible validation options."""
    return f"Energy per item: {energy / count}"

Requirements

  • Python ≥ 3.8

  • Pint ≥ 0.20

  • Pydantic ≥ 2.0 (optional, for dataclass integration)


Testing

git clone https://github.com/MartinPdeS/TypedUnit.git
cd TypedUnit
pip install -e ".[testing]"
pytest

Contributing

TypedUnit is open source and contributions are welcome! Whether you’re fixing bugs, adding new unit types, or improving documentation, your help is appreciated.

Author: Martin Poinsinet de Sivry-Houle

Email: martin.poinsinet-de-sivry@polymtl.ca

Metadata

Release files for TypedUnit 0.4.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.4.0
File Size Uploaded Provenance Actions
typedunit-0.4.0.tar.gz 19.5 kB Without provenance Details for typedunit-0.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 32.8 kB

Release files / typedunit-0.4.0.tar.gz

Download URL typedunit-0.4.0.tar.gz
Size 19.5 kB
Tags Source
SHA-256 checksum
How to use checksums
95a18481142492b2a58eb030882eeb6cc7ac99a5eb21af91d179e4a3e673e7ac
BLAKE2b-256 checksum
How to use checksums
76faeef77dfb6df0cd1fad1c16b565d0443555b9543187f058ef6e0db78ef8c6
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.4.0-py3-none-any.whl

Download URL typedunit-0.4.0-py3-none-any.whl
Size 13.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3b10ebb91db3761f6f898a842ae9786860834b647338b915d4bf47e7b08fe1cc
BLAKE2b-256 checksum
How to use checksums
53c24b5b5e143579b68f822ec15ea4c69c0d2553078171f651e69fde264be548
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.4.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