Cleanup previous PR

This commit is contained in:
Kovid Goyal
2025-03-19 21:25:02 +05:30
parent 80db9b4734
commit 0db9b882fe
4 changed files with 33 additions and 27 deletions

View File

@@ -67,17 +67,17 @@ def unit_float(x: ConvertibleToNumbers) -> float:
return max(0, min(float(x), 1))
def number_with_unit(x: str, default_unit: str = '') -> tuple[float, str]:
mat = number_unit_pat.match(x)
exception = None
if mat is not None:
def number_with_unit(x: str, default_unit: str, *extra_units: str) -> tuple[float, str]:
if (mat := number_unit_pat.match(x)) is not None:
try:
value, unit = float(mat.group(1)), mat.group(2)
unit = default_unit if not unit else unit
return value, unit
value = float(mat.group(1))
except Exception as e:
exception = e
raise ValueError(f'Invalid number with unit config option provided: {x if exception is None else exception}')
raise ValueError(f'Not a number: {x} with error: {e}')
unit = mat.group(2) or default_unit
if unit != default_unit and unit not in extra_units:
raise ValueError(f'Not a valid unit: {x}. Allowed units are: {default_unit}, {", ".join(extra_units)}')
return value, unit
raise ValueError(f'Invalid number with unit: {x}')
def to_bool(x: str) -> bool: