Skip to main content

A package wrapping pint for handling typed units in Python.

Project description

Python version Documentation Status Unittest coverage PyPi PyPi download statistics

Type-safe physical units for Python

TypedUnits 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 for unit validation based on type 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 TypedUnits import Energy, Time, Power, validate, 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

@validate_units
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 TypedUnits

Basic Usage

Unit Type Checking

from TypedUnits 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 TypedUnits 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 TypedUnits 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

TypedUnits 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 TypedUnits 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 TypedUnits 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/TypedUnits.git
cd TypedUnits
pip install -e ".[testing]"
pytest

Contributing

TypedUnits 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


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

typedunit-0.0.5.tar.gz (286.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

typedunit-0.0.5-py3-none-any.whl (9.1 kB view details)

Uploaded Python 3

File details

Details for the file typedunit-0.0.5.tar.gz.

File metadata

  • Download URL: typedunit-0.0.5.tar.gz
  • Upload date:
  • Size: 286.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.23

File hashes

Hashes for typedunit-0.0.5.tar.gz
Algorithm Hash digest
SHA256 cbcc9f1e9103df6cff889e26b27c6603ab5a636c1cb40b3c9ddb746e5dd8e458
MD5 08f481fdc8ce1fddd40620ec90652b7d
BLAKE2b-256 b894b18cbc4a42f6d156776a490d041155f789c3aeedd22aa1952e443347005a

See more details on using hashes here.

File details

Details for the file typedunit-0.0.5-py3-none-any.whl.

File metadata

  • Download URL: typedunit-0.0.5-py3-none-any.whl
  • Upload date:
  • Size: 9.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.23

File hashes

Hashes for typedunit-0.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 bd7d951bf7ed4760cbf326d59d3f3bb1abeda6a6635749c815e57f1499b7cdec
MD5 bd459418cf111611f7fb9c38baafd9eb
BLAKE2b-256 02d90c62b5c207c9dcbbf6089e2ea6c7adad3d129c0e3ef7dc9ddd353fd05fb7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page