brails.utils.unit_converter module

This module defines a class for performing unit parsing and conversions.

UnitConverter()

A utility class for converting values between different units.

class brails.utils.unit_converter.UnitConverter

Bases: object

A utility class for converting values between different units.

This class provides static methods for unit conversion across three categories: - Length (e.g., meters to feet) - Area (e.g., square kilometers to square yards) - Weight (e.g., kilograms to pounds)

Supported unit types and examples:
Length units:

‘m’, ‘km’, ‘cm’, ‘mm’, ‘in’, ‘ft’, ‘yd’, ‘mi’

Area units (derived from squared base length units):

‘m2’, ‘km2’, ‘cm2’, ‘mm2’, ‘in2’, ‘ft2’, ‘yd2’, ‘mi2’

Weight units:
  • Metric: ‘mg’, ‘g’, ‘kg’, ‘ton’ (metric ton = 1,000 kg)

  • Imperial:

    ‘oz’ = ounce ‘lb’ = pound ‘ton_us’ = US short ton (2,000 lb) ‘ton_uk’ = UK long ton (2,240 lb)

Key Features:
  • Supports standard and alias unit names (e.g., “meter”, “m”, “kg”).

  • Automatically validates unit category compatibility.

  • Converts via standardized base units:
    • Meters for length

    • Square meters for area

    • Kilograms for weight

Methods:
convert_length(value, from_unit, to_unit) -> float:

Convert a numeric value between supported length units.

convert_area(value, from_unit, to_unit) -> float:

Convert a numeric value between supported area units (e.g., m2 to ft2).

convert_weight(value, from_unit, to_unit) -> float:

Convert a numeric value between supported weight units (e.g., kg to lb).

convert_unit(value, from_unit, to_unit) -> float:

Auto-detect the category (length, area, or weight) and convert between compatible units.

normalize_unit(unit) -> str:

Standardize unit strings and resolve common aliases (e.g., “meters” is “m”).

get_unit_type(unit) -> str:

Return the category of a unit (‘length’, ‘area’, or ‘weight’).

unit_valid(unit, expected_unit_type) -> bool:

Check if a unit belongs to the expected category and raise an error if not.

parse_units(input_dict, unit_defaults) -> dict:

Extract and validate units from a dictionary, applying defaults where needed.

get_supported_units(unit_type=’all’) -> str:

Return a formatted string listing supported units for a given type or all types.

Notes:
  • Area conversions are based on the square of length conversions.

  • Weight conversion uses kilograms as the internal reference unit.

  • An error is raised if units are mismatched or unrecognized.

Example Usage:
>>> UnitConverter.convert_length(10, 'm', 'ft')
32.8084
>>> UnitConverter.convert_area(100, 'm2', 'ft2')
1076.391041671
>>> UnitConverter.convert_weight(1, 'ton', 'lb')
2204.6226218487757
>>> UnitConverter.convert_unit(5, 'km', 'mi')
3.106855
>>> UnitConverter.convert_unit(2500, 'g', 'lb')
5.51156
>>> UnitConverter.normalize_unit('Meters')
'm'
>>> UnitConverter.get_unit_type('yd2')
'area'
>>> UnitConverter.unit_valid('oz', 'weight')
True
>>> UnitConverter.parse_units({'weight': 'lb'},
                              {'length': 'm', 'weight': 'kg'})
{'length': 'm', 'weight': 'lb'}
>>> 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
static convert_area(value: float, from_unit: str, to_unit: str) float

Convert an area value from one unit to another.

Supported units: ‘m2’, ‘km2’, ‘cm2’, ‘mm2’, ‘in2’, ‘ft2’, ‘yd2’, ‘mi2’

Args:
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’).

Returns:
float:

Converted area value in the target unit.

Raises:
ValueError:

If either unit is unsupported.

static convert_length(value: float, from_unit: str, to_unit: str) float

Convert a length value from one unit to another.

Supported units: ‘m’, ‘km’, ‘cm’, ‘mm’, ‘in’, ‘ft’, ‘yd’, ‘mi’

Args:
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.

Returns:
float:

Converted value in the target unit.

Raises:
ValueError:

If either unit is unsupported.

static convert_unit(value: float, from_unit: str, to_unit: str)

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.

Args:
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.

Returns:
float:

The value converted to the target unit.

Raises:
ValueError:

If the units belong to different categories (e.g., length vs weight), are unrecognized, or if the unit type is unsupported.

static convert_weight(value: float, from_unit: str, to_unit: str)

Convert a weight value from one unit to another.

Supported units: ‘mg’, ‘g’, ‘kg’, ‘ton’ (metric ton), ‘oz’, ‘lb’, ‘ton_us’, ‘ton_uk’

Args:
value(float):

The numeric value to convert.

from_unit(str):

The source unit.

to_unit(str):

The target unit.

Returns:
float:

Converted value in the target unit.

Raises:
ValueError:

If either unit is unsupported.

get_supported_units() str

Return a formatted string listing supported units for a unit type.

Args:
unit_type (str):

The type of unit to retrieve (‘length’, ‘area’, ‘weight’, or ‘all’). Defaults to ‘all’.

Returns:
str:

A human-readable string of supported units.

static get_unit_type(unit: str)

Identify unit type as ‘length’, ‘area’, or ‘weight’.

Returns:
str:

Unit type.

Raises:
ValueError:

If unit is not recognized.

static normalize_unit(unit: str)

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”).

Args:
unit (str):

The input unit string to normalize.

Returns:
str:

The standardized unit string. If no alias is found, returns the cleaned input.

static parse_units(input_dict: dict, unit_defaults: dict) dict

Parse and validate units from input_dict based on defaults.

Args:
input_dict (dict):

Dictionary with unit inputs.

unit_defaults (dict):

Default unit values for each unit type.

Returns:
dict:

Validated units per type (e.g., {‘length’: ‘ft’, ‘weight’: ‘lb’}).

Raises:
ValueError:

If a unit is invalid.

static unit_valid(unit: str, expected_unit_type: str) bool

Validate that a unit belongs to the expected unit type.

Args:
unit (str):

The unit to check (e.g., ‘m’, ‘kg’, ‘ft2’).

expected_unit_type (str):

The expected type (‘length’, ‘area’, or ‘weight’).

Returns:
bool:

True if the unit matches the expected type. False otherwise