liveBook · Manning

Quantity

As explained in Build Python Web Apps with Streamlit

A quantity is a measurable amount that can be represented numerically and associated with a unit.

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

How Build Python Web Apps with Streamlit covers it

How deep it goes
Defines a quantity’s stored attributes and works through configuration and backend lookups, without pursuing measurement theory.
Examples
Uses mass and length configurations and a mock-up with a quantity selector and two unit menus.
What it assumes
Builds on Python dictionaries and introduces dataclasses as a way to represent quantities and units.
What you can do after
Build it from scratch with Python dataclasses and a configuration-driven backend that lists quantities and units and converts values.
How it connects
Connects quantities to units, standard units, conversion factors, configuration files, and frontend–backend interactions.

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.