saiunit.typing module#
Unit-aware type annotations for saiunit.
This module provides type aliases and annotation helpers that let you
express physical-unit constraints directly in Python type hints, using
PEP 593 (typing.Annotated).
Quick start#
import saiunit as u
from saiunit.typing import QuantityLike, UnitLike
# Annotate with a specific unit
def kinetic_energy(m: u.Quantity[u.kilogram], v: u.Quantity[u.meter / u.second]) -> u.Quantity[u.joule]:
return 0.5 * m * v ** 2
# Annotate with a physical type (dimension) string
def travel_time(distance: u.Quantity["length"], speed: u.Quantity["speed"]) -> u.Quantity["time"]:
return distance / speed
Subscript syntax#
Quantity[x] is a shorthand that produces a type usable with both
isinstance and typing.Annotated:
Quantity[u.meter]— matches anyQuantitywith length dimensionQuantity["length"]— same, using a physical type string
isinstance support#
x = 2.0 * u.km
from saiunit.typing import quantity_type
isinstance(x, quantity_type(u.meter)) # True (same dimension)
isinstance(x, quantity_type("length")) # True
isinstance(x, quantity_type("mass")) # False
from saiunit.typing import PhysicalType
isinstance(x, PhysicalType("length")) # True
Pre-built aliases#
Common physical types are available as ready-made aliases:
from saiunit.typing import LENGTH, SPEED, VOLTAGE
def displacement(v: SPEED, t: saiunit.typing.TIME) -> LENGTH:
return v * t
Runtime validation#
The validate_units() decorator checks that Quantity arguments
match the annotated units/dimensions at call time.
from saiunit.typing import validate_units
@validate_units
def ohms_law(V: u.Quantity[u.volt], R: u.Quantity[u.ohm]) -> u.Quantity[u.amp]:
return V / R
Physical Type Utilities#
Create a physical type that works with both type annotations and |
|
Check whether obj is a |
|
Return a runtime-checkable Quantity type for |
Core Type Aliases#
Type alias for objects that can be converted to a |
|
Type alias for objects that can be interpreted as a |
|
Type alias for objects that can be interpreted as a |
Pre-built Physical-Type Aliases#
Runtime Validation#
Decorator that validates |