A quantity is a measurable amount expressed with a number and a unit. In a unit converter, quantities are also grouped by what they measure: mass and length are different categories, each with its own units. section 3.6.2 section 3.4.1
To convert a value, choose units that measure the same type of quantity. A category selector can limit both unit menus to relevant choices, so a user converting mass sees units such as grams and kilograms rather than meters. section 3.4.1 section 3.6.2
Each quantity has a set of units and one designated standard unit. Each unit stores an abbreviation and a conversion factor relative to that standard. A Python dataclass makes these attributes explicit. section 3.6.2
Listing 3.3 The Quantity dataclass in quantity.py
from dataclasses import dataclass
from typing import Dict
from unit import Unit
@dataclass
class Quantity:
std_unit: str
units: Dict[str, Unit]
The Quantity dataclass stores the standard unit’s name and a dictionary of Unit objects. section 3.6.2
"Mass": Quantity(
std_unit="Kilograms",
units={
"Kilograms": Unit(abbrev="kg", value_in_std_units=1),
"Grams": Unit(abbrev="g", value_in_std_units=0.001),
"Pounds": Unit(abbrev="lb", value_in_std_units=0.453592),
"Ounces": Unit(abbrev="oz", value_in_std_units=0.0283495),
# Add more units here
}
)
The mass configuration designates kilograms as standard and records factors for grams, pounds, and ounces. section 3.6.2
Converting grams to kilograms
For mass, kilograms have a standard-unit factor of 1 and grams have a factor of 0.001. To convert 1,000 grams to kilograms, multiply by 0.001 and divide by 1: the result is 1 kilogram. The same two-step approach converts between other units in the quantity. section 3.6.2
Keep quantity names, units, and factors together in one configuration file. The interface and backend can look up that information instead of hard-coding individual quantities, making it easier to add units without changing several parts of the app. section 3.5.2 section 3.6.2
