Skip to main content

Unit-Aware Arithmetic (Python)

A type-safe dimensional arithmetic library that tracks units at runtime and prevents invalid operations.

Features

  • Type-safe dimensional analysis: Prevents incompatible unit operations
  • Zero dependencies: Core functionality has no external dependencies
  • Comprehensive unit coverage: SI, imperial, and derived units
  • Arithmetic operations: Add, subtract, multiply, divide with unit tracking
  • Unit conversion: Automatic and explicit conversion between compatible units
  • Clear error messages: Helpful errors for incompatible operations
  • Production-ready: Comprehensive test coverage (>95%)

Installation

pip install -e .

Quick Start

from dimensional import Quantity, units

# Create quantities with units
distance = Quantity(100, units.meter)
time = Quantity(9.58, units.second)

# Arithmetic operations with automatic unit tracking
speed = distance / time
print(speed)  # 10.438413361169102 m/s

# Unit conversion
distance_km = distance.to(units.kilometer)
print(distance_km)  # 0.1 km

# Type-safe operations - this will raise an error!
try:
    distance + time  # IncompatibleUnitsError
except Exception as e:
    print(f"Error: {e}")

Usage Examples

Basic Arithmetic

from dimensional import Quantity, units

# Addition (same dimension required)
d1 = Quantity(5, units.meter)
d2 = Quantity(3, units.meter)
total = d1 + d2  # 8.0 m

# Multiplication creates derived units
area = Quantity(5, units.meter) * Quantity(3, units.meter)
print(area)  # 15.0 m·m

# Division creates derived units
velocity = Quantity(100, units.meter) / Quantity(10, units.second)
print(velocity)  # 10.0 m/s

Unit Conversion

from dimensional import Quantity, units

# Length conversion
distance = Quantity(1, units.mile)
distance_km = distance.to(units.kilometer)
print(distance_km)  # 1.60934 km

# Temperature conversion
temp_c = Quantity(0, units.celsius)
temp_k = temp_c.to(units.kelvin)
print(temp_k)  # 273.15 K

# Mass conversion
mass_lb = Quantity(10, units.pound)
mass_kg = mass_lb.to(units.kilogram)
print(mass_kg)  # 4.53592 kg

Physics Calculations

from dimensional import Quantity, units

# Calculate velocity
distance = Quantity(100, units.meter)
time = Quantity(9.58, units.second)
velocity = distance / time
print(f"Velocity: {velocity}")

# Calculate force (F = ma)
mass = Quantity(10, units.kilogram)
acceleration = Quantity(9.8, units.meter_per_second_squared)
force = mass * acceleration
print(f"Force: {force}")

# Calculate kinetic energy (KE = 1/2 * m * v²)
mass = Quantity(2, units.kilogram)
velocity = Quantity(10, units.meter_per_second)
ke = 0.5 * mass * (velocity ** 2)
print(f"Kinetic Energy: {ke}")

Comparison Operations

from dimensional import Quantity, units

d1 = Quantity(100, units.centimeter)
d2 = Quantity(1, units.meter)

# Automatic conversion for comparison
print(d1 == d2)  # True
print(d1 < Quantity(2, units.meter))  # True

Available Units

Length

  • meter, kilometer, centimeter, millimeter
  • inch, foot, yard, mile

Mass

  • kilogram, gram, milligram, tonne
  • pound, ounce

Time

  • second, minute, hour, day

Temperature

  • kelvin, celsius, fahrenheit

Current

  • ampere, milliampere

Derived Units

  • newton (force)
  • joule, kilojoule (energy)
  • watt, kilowatt (power)
  • pascal, kilopascal (pressure)
  • meter_per_second, kilometer_per_hour (velocity)
  • meter_per_second_squared (acceleration)

Error Handling

The library provides clear error messages for invalid operations:

from dimensional import Quantity, units, IncompatibleUnitsError

distance = Quantity(100, units.meter)
time = Quantity(10, units.second)

try:
    # This will raise IncompatibleUnitsError
    result = distance + time
except IncompatibleUnitsError as e:
    print(e)  # "Cannot add m and s: incompatible dimensions"

Testing

Run the test suite:

pytest test_dimensional.py -v

Run with coverage:

pytest test_dimensional.py --cov=dimensional --cov-report=html

Type Checking

This library includes type hints. Run type checking with:

mypy dimensional.py

Design Principles

  1. Zero Dependencies: Core functionality has no external dependencies
  2. Type Safety: Prevents invalid operations at runtime
  3. Clear Errors: Actionable error messages
  4. Production Ready: Comprehensive test coverage
  5. Performance: Efficient implementation with minimal overhead

API Reference

Dimension

Represents the dimensional formula of a unit (e.g., L^1 T^-2 for acceleration).

Unit

Represents a unit of measurement with its dimension and conversion factor.

Quantity

A numeric value with an associated unit. Supports:

  • Arithmetic: +, -, *, /, **, - (negation), abs()
  • Comparison: ==, !=, <, <=, >, >=
  • Conversion: .to(target_unit)

units

Namespace containing all predefined units.

License

MIT License

Contributing

Contributions are welcome! Please ensure:

  • All tests pass
  • Code coverage remains >90%
  • Type hints are included
  • Documentation is updated

Changelog

1.0.0 (2026-08-28)

  • Initial release
  • Support for SI and imperial units
  • Comprehensive dimensional analysis
  • Temperature conversion with offset handling
  • Full test coverage

Download files

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

Source Distribution

unit_aware_arithmetic-1.0.0.tar.gz (11.4 kB view details)

Uploaded Source

Built Distribution

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

unit_aware_arithmetic-1.0.0-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file unit_aware_arithmetic-1.0.0.tar.gz.

File metadata

  • Download URL: unit_aware_arithmetic-1.0.0.tar.gz
  • Upload date:
  • Size: 11.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.5

File hashes

Hashes for unit_aware_arithmetic-1.0.0.tar.gz
Algorithm Hash digest
SHA256 b2ad2121e90346a90ff87e8fc1e999bac2fb0054f21c65e89d24ddb029088785
MD5 f41d99f6a6c96409ce43913f573dd0cf
BLAKE2b-256 b90b43560634fb774c9c12aeb4d6b72fe8a01bcab970ac4ff013107509e6c661

See more details on using hashes here.

File details

Details for the file unit_aware_arithmetic-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for unit_aware_arithmetic-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 699b557bb3102db8907df1a937e5635e5ba0e3ac3138750ce30a70a0efe295d2
MD5 6b818c4d440dd9d0fe2898c0aa7ada6e
BLAKE2b-256 cf390b61e4d430bce2c26a770c1b7e53d3081fd11cae41893291c3131d8ea552

See more details on using hashes here.

Release history Release notifications | RSS feed

2.0.0

2 files

This release

1.0.0 This release

2 files

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