brails.utils.unit_converter module
This module defines a class for performing unit parsing and conversions.
A utility class for converting values between different measurement units. |
- class brails.utils.unit_converter.UnitConverter
Bases:
object
A utility class for converting values between different measurement units.
The UnitConverter provides static methods for converting values across three main measurement categories: length, area, and weight. All conversions are performed via standardized base units to ensure consistency and accuracy.
- Base units:
Length: meters (m)
Area: square meters (m²)
Weight: kilograms (kg)
- Supported Units:
- Length:
m, meter, metre km, kilometer, kilometre cm, centimeter, centimetre mm, millimeter, millimetre in, inch ft, foot, feet yd, yard mi, mile
- Area (derived from squared length units):
m2, square_meter km2, square_kilometer cm2, square_centimeter mm2, square_millimeter in2, square_inch ft2, square_foot yd2, square_yard mi2, square_mile
- Weight:
- Metric:
mg, milligram g, gram kg, kilogram ton, metric_ton (1000 kg)
- Imperial:
oz, ounce lb, pound ton_us, short_ton (2000 lb) ton_uk, long_ton (2240 lb)
- Key Features:
Supports standard and alias unit names.
Validates unit category compatibility.
Converts via base units.
Area conversions use squared length conversions.
Weight conversions use kilograms as reference.
Optional rounding precision for conversion results.
Raises errors for mismatched or unsupported units.
Note
All conversions are first mapped to the category’s base unit, then converted to the target unit.
Passing None or NaN values returns them unchanged.
Unit names are case-insensitive.
Importing instructions:
The following line is suggested to import the
UnitConverter
.from brails.utils import UnitConverter
- static convert_area(value, from_unit, to_unit, precision=2)
Convert an area value from one unit to another.
Supported units: ‘m2’, ‘km2’, ‘cm2’, ‘mm2’, ‘in2’, ‘ft2’, ‘yd2’, ‘mi2’
- Parameters:
value (float) – The numeric area value to convert.
from_unit (str) – The current area unit(e.g., ‘m2’).
to_unit (str) – The desired area unit(e.g., ‘ft2’).
precision (int, optional) – Number of decimal places to round the result to. Defaults to 2.
- Returns:
Converted value in the target unit, rounded to the specified
precision
.- Return type:
float
- Raises:
ValueError – If either unit is unsupported.
Examples
>>> UnitConverter.convert_area(100, 'm2', 'ft2') 1076.39
>>> UnitConverter.convert_area(100, 'm2', 'ft2', precision=5) 1076.39104
- static convert_length(value, from_unit, to_unit, precision=2)
Convert a length value from one unit to another.
Supported units: ‘m’, ‘km’, ‘cm’, ‘mm’, ‘in’, ‘ft’, ‘yd’, ‘mi’
- Parameters:
value (float) – The numeric value to convert.
from_unit (str) – The current unit of the value.
to_unit (str) – The desired unit to convert to.
precision (int, optional) – Number of decimal places to round the result to. Defaults to 2.
- Returns:
Converted value in the target unit, rounded to the specified
precision
.- Return type:
float
- Raises:
ValueError – If either unit is unsupported.
Examples
>>> UnitConverter.convert_length(10, 'm', 'ft') 32.81
>>> UnitConverter.convert_length(10, 'm', 'ft', precision=4) 32.8084
- static convert_unit(value, from_unit, to_unit, precision=2)
Convert a numerical value between compatible units.
This method supports conversions across three unit categories: length, area, and weight. Unit aliases(e.g.,
'kg'
for'kilogram'
) are supported. The function automatically detects the category of the input and output units and ensures they are compatible.- Parameters:
value (float) – The numerical value to convert.
from_unit (str) – The source unit (e.g.,
'meter'
,'sqft'
,'kg'
). Aliases are supported.to_unit (str) – The target unit for conversion. Must be in the same category as
from_unit
.precision (int, optional) – Number of decimal places to round the result to. Defaults to 2.
- Returns:
Converted value in the target unit, rounded to the specified
precision
.- Return type:
float
- Raises:
ValueError – If the units belong to different categories (e.g., length vs weight), are unrecognized, or if the unit type is unsupported.
Examples
>>> UnitConverter.convert_unit(5, 'km', 'mi') 3.11
>>> UnitConverter.convert_unit(2500, 'g', 'lb', precision=3) 5.512
- static convert_weight(value, from_unit, to_unit, precision=2)
Convert a weight value from one unit to another.
Supported units: ‘mg’, ‘g’, ‘kg’, ‘ton’ (metric ton), ‘oz’, ‘lb’, ‘ton_us’, ‘ton_uk’
- Parameters:
value (float) – The numeric value to convert.
from_unit (str) – The source unit.
to_unit (str) – The target unit.
precision (int, optional) – Number of decimal places to round the result to. Defaults to 2.
- Returns:
Converted value in the target unit, rounded to the specified
precision
.- Return type:
float
- Raises:
ValueError – If either unit is unsupported.
Examples
>>> UnitConverter.convert_weight(1, 'ton', 'lb') 2204.62
>>> UnitConverter.convert_weight(1, 'ton', 'lb', precision=1) 2204.6
- get_supported_units()
Return a formatted string listing supported units for a unit type.
- Parameters:
unit_type (str) – The type of unit to retrieve(
'length'
,'area'
,'weight'
, or'all'
). Defaults to'all'
.- Returns:
A human-readable string of supported units.
- Return type:
str
Examples
>>> print(UnitConverter.get_supported_units()) Length: cm, ft, in , km, m, mi, mm, yd Area: cm2, ft2, in2, km2, m2, mi2, mm2, yd2 Weight: g, kg, lb, mg, oz, ton, ton_uk, ton_us
>>> print(UnitConverter.get_supported_units(unit_type='length')) Length: cm, ft, in , km, m, mi, mm, yd
- static get_unit_type(unit)
Identify unit type as
'length'
,'area'
, or'weight'
.- Returns:
Unit type.
- Return type:
str
- Raises:
ValueError – If unit is not recognized.
Example
>>> UnitConverter.get_unit_type('yd2') 'area'
- static normalize_unit(unit)
Normalize unit name by reformatting and resolving aliases.
This function ensures consistent internal representation of units, allowing users to use common names or variations(e.g.,
'meters'
,'LBS'
,'square foot'
) which will be mapped to standard short forms (e.g.,'m'
,'lb'
,'ft2'
).- Parameters:
unit (str) – The input unit string to normalize.
- Returns:
The standardized unit string. If no alias is found, returns the cleaned input.
- Return type:
str
Examples
>>> UnitConverter.normalize_unit('Meters') 'm'
>>> UnitConverter.normalize_unit('kilogram') 'kg'
- static parse_units(input_dict, unit_defaults)
Parse and validate units from input_dict based on defaults.
- Parameters:
input_dict (dict) – Dictionary with unit inputs.
unit_defaults (dict) – Default unit values for each unit type.
- Returns:
Validated units per type(e.g.,
{'length': 'ft', 'weight': 'lb'}
).- Return type:
dict
- Raises:
ValueError – If a unit is invalid.
Example
>>> UnitConverter.parse_units( ... input_dict={'weight': 'lb'}, ... unit_defaults={'length': 'm', 'weight': 'kg'} ...) {'length': 'm', 'weight': 'lb'}
- static unit_valid(unit, expected_unit_type)
Validate that a unit belongs to the expected unit type.
- Parameters:
unit (str) – The unit to check(e.g.,
'm'
,'kg'
,'ft2'
).expected_unit_type (str) – The expected type(
'length'
,'area'
, or'weight'
).
- Returns:
True
if the unit matches the expected type.False
otherwise- Return type:
bool
Examples
>>> UnitConverter.unit_valid('oz', 'weight') True
>>> UnitConverter.unit_valid('m2', 'length') False