In a unit converter, a quantity identifies what is being measured, such as mass or length. It is separate from the numeric value: a user might enter a value, choose the mass quantity, and then select units for that value. section 3.6.2 section 3.4.1
The selected quantity determines which units are available. Both the starting and destination units must measure that same quantity; choosing a category first keeps unrelated units out of the unit menus. section 3.4.1
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]
A Quantity stores its standard unit and a dictionary of available units. Each Unit separately stores an abbreviation and a conversion factor relative to that standard. section 3.6.2
Mass in a converter
Mass uses kilograms as its standard unit. Its configuration includes grams, pounds, and ounces, each with a factor expressed in kilograms. To convert a value, the backend looks up both units under Mass, multiplies by the starting unit’s factor, and divides by the destination unit’s factor. section 3.6.2
Keep quantity names, units, and factors in one configuration file rather than hard-coding them into the interface. Then the interface and backend can list supported quantities and units from that configuration, making additions easier to maintain. section 3.5.2 section 3.6.2
