liveBook · Manning

Unit of measurement

As explained in Build Python Web Apps with Streamlit

A unit of measurement is a standardized quantity used to express the magnitude of a measurable property.

A unit of measurement expresses a value for a particular kind of quantity. In a conversion app, a user enters a number, chooses its current unit and chooses a target unit. Both units must measure the same kind of quantity: the app offers units from the selected category, then displays the converted value. section 3.4.1

Convert pounds to ounces

One pound equals 16 ounces, so 5 pounds becomes 5 × 16 = 80 ounces. The number 16 is the pound-to-ounce conversion factor. For the reverse direction, divide by 16. section 3.5.1

Storing a factor for every possible pair becomes cumbersome. Instead, choose one standard unit per quantity category—meters for length, for example—and store each other unit’s value in that standard unit. To convert between two units, first convert to the standard unit, then to the target unit. section 3.5.1

Keep unit names, abbreviations and factors together in one configuration file. This gives developers a single place to add a unit without hard-coding its name into the interface. A Python Unit dataclass holds an abbreviation and a value in standard units; a Quantity identifies its standard unit and contains its available units. section 3.5.2 section 3.6.2

def convert_value(
        quantity_name: str,
        from_unit_name: str,
        to_unit_name: str,
        value: float) -> Result:
    quantity = unit_config[quantity_name]
    from_unit = quantity.units[from_unit_name]
    to_unit = quantity.units[to_unit_name]

    # Two-step conversion: from-unit to standard unit, then to to-unit
    value_in_to_units = (value *
                         from_unit.value_in_std_units /
                         to_unit.value_in_std_units)

    return Result(from_unit, to_unit, value, value_in_to_units)

The backend multiplies the input by the source unit’s value in standard units, then divides by the target unit’s value in standard units. section 3.6.2

How Build Python Web Apps with Streamlit covers it

How deep it goes
Works through conversion factors, standard units, configuration and backend calculation.
Examples
Uses pounds to ounces, yards to feet, and a mass-and-length unit configuration.
What it assumes
Assumes basic Python editing while introducing dataclasses for units and quantities.
What you can do after
Build it from scratch as a configurable converter that calculates between units of the same quantity.
How it connects
Connects units to quantities, conversion factors, standard units, dataclasses and configuration files.

Also explained in

Compare how 2 books explain unit of measurement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.