Skip to content

ucon.checking

Runtime dimension enforcement via decorator.

ucon.checking

Runtime dimensional validation for functions accepting Number arguments.

Provides the @enforce_dimensions decorator, which validates Number arguments against their Number[Dimension.X] annotations at call time.

enforce_dimensions(fn=None, *, system=None)

Validate and coerce Number arguments against their annotations.

Usable as a bare decorator (@enforce_dimensions) or as a factory (@enforce_dimensions(system=sys)).

Parameters annotated as Number[Dimension.X] are validated for dimensional compatibility. Parameters annotated as Number[kind] are validated for kind identity (or lattice descendancy). Joint annotations Number[Dimension.X, kind] check both. Plain Number parameters and non-Number parameters are ignored.

Cross-basis inputs (e.g. CGS dyne for an SI force constraint) are automatically coerced to their SI equivalents so that arithmetic inside the function body does not raise on mixed bases.

Checks are precomputed at decoration time. Per-call overhead is one dict lookup and one comparison per constrained parameter.

Parameters

fn : callable, optional The function to wrap. When None, returns a decorator factory (this is how the system= keyword form is supported). system : UnitSystem, optional When supplied, system.conversion_graph and system.basis_graph replace the module-level default graphs used for cross-basis compatibility checks and SI coercion.

Returns

callable Wrapped function with dimensional validation on entry, or a decorator factory when called with keyword-only arguments.

Raises

TypeError If a constrained argument is not a Number instance. ValueError If a Number's dimension or kind does not match the annotated constraint.

Example

@enforce_dimensions ... def speed(distance: Number[Dimension.length], time: Number[Dimension.time]) -> Number: ... return distance / time

from ucon.system import active @enforce_dimensions(system=active()) ... def kinetic(m: Number[Dimension.mass], v: Number[Dimension.velocity]) -> Number: ... return 0.5 * m * v * v