pyunitwizard.ensure_quantity#

pyunitwizard.ensure_quantity(value, dimensionality=None, to_unit=None, standardized=True, parser=None, caller=None)[source]#

Return value as a validated quantity, or raise.

This is the canonical “digest a length/mass/time/… argument” helper: it accepts any PyUnitWizard-recognized quantity form (a unit-bearing string, or a pint/openmm/astropy/unyt quantity), optionally checks its physical dimensionality, and returns it standardized (or in to_unit). Bare numbers are rejected, so a value meant as one unit is never silently reinterpreted as another.

Parameters:
  • value (Any) – A quantity, or a unit-bearing string (e.g. "3.5 angstroms"). Bare numbers (int/float/array/list) are rejected.

  • dimensionality (dict, optional) – Required dimensionality, e.g. {'[L]': 1} for a length. If given and the quantity does not match, an ArgumentError is raised.

  • to_unit (str, optional) – If given, the quantity is returned in this unit instead of the configured standard unit.

  • standardized (bool, default True) – When True (and to_unit is None) the quantity is returned in the configured standard units. When False (and to_unit is None) the quantity is returned unchanged (still validated).

  • parser (str, optional) – Parser used for string quantities.

  • caller (str, optional) – Name of the calling function, used to enrich error messages.

Returns:

The validated quantity, standardized or converted to to_unit.

Return type:

Any

Raises:

ArgumentError – If value is not a quantity, or its dimensionality does not match.