Skip to content

ucon.parsing

String parsing for human-readable quantity expressions.

ucon.parsing

Recursive descent parser for complex unit expressions.

Supports: - Parentheses: W/(m²*K) - Chained division: mg/kg/d - Unicode operators: ·, , × - Unicode superscripts: ⁰¹²³⁴⁵⁶⁷⁸⁹⁻ - ASCII equivalents: *, ^, -

Grammar

::

unit_expr  := term (('*' | '·' | '/' | '⋅') term)*
term       := factor ('^' exponent)?
factor     := '(' unit_expr ')' | scale_unit
scale_unit := SCALE? UNIT
exponent   := INTEGER | '-' INTEGER | '⁻'? SUPERSCRIPT+

ParseError

Bases: ValueError

Raised when unit expression parsing fails.

parse_unit_expression(expression, lookup_fn, unit_factor_cls, unit_product_cls)

Parse a unit expression string into a UnitProduct.

This is the main entry point for parsing complex unit expressions.

Parameters:

Name Type Description Default
expression str

The unit expression (e.g., "W/(m²*K)", "mg/kg/d").

required
lookup_fn Callable[[str], Tuple['Unit', 'Scale']]

Function to resolve unit names to (Unit, Scale) tuples.

required
unit_factor_cls type

The UnitFactor class.

required
unit_product_cls type

The UnitProduct class.

required

Returns:

Type Description
'UnitProduct'

A UnitProduct representing the parsed expression.

Raises:

Type Description
ParseError

If the expression is malformed.

Examples:

>>> parse_unit_expression("m/s²", lookup_fn, UnitFactor, UnitProduct)
<UnitProduct m/s²>

parse(s)

Parse a quantity string into a Number.

Supports various formats: - Basic quantities: "60 mph", "9.81 m/s^2", "1.5 kg" - Pure numbers: "100", "3.14159" (returns dimensionless Number) - Scientific notation: "1.5e3 m", "6.022e23" - Negative values: "-273.15 °C" - Uncertainty with ±: "1.234 ± 0.005 m" - Uncertainty with +/-: "1.234 +/- 0.005 m" - Parenthetical uncertainty: "1.234(5) m" (means 1.234 ± 0.005) - Uncertainty with unit: "1.234 m ± 0.005 m"

The function respects context from using_graph() for unit resolution.

Parameters:

Name Type Description Default
s str

The quantity string to parse.

required

Returns:

Type Description
'Number'

A Number representing the parsed quantity.

Raises:

Type Description
ValueError

If the string cannot be parsed.

UnknownUnitError

If the unit cannot be resolved.

Examples:

>>> parse("60 mph")
<60 mph>
>>> parse("1.234 ± 0.005 m")
<1.234 ± 0.005 m>
>>> parse("9.81 m/s^2")
<9.81 m/s²>
>>> parse("100")
<100>