Unit-Aware Measurements
The `measurement` library (also known as `python-measurement`) provides easy-to-use unit-aware measurement objects in Python. It allows for manipulation and conversion between various SI, US, and Imperial units for quantities like Distance, Weight, Volume, Temperature, Energy, Speed, and Time. The library is currently active, with its latest release (3.2.2) on January 10, 2023, and maintains a stable API.
Warnings
- gotcha Measurements are stored internally as floating-point numbers of a (generally) reasonable SI unit. This can lead to slight inaccuracies due to the nature of floating-point representation. Do not use this library for applications requiring extreme precision, such as navigation algorithms for critical systems.
- gotcha When defining custom `MeasureBase` subclasses, ensure `STANDARD_UNIT` and `UNITS` are correctly configured. Incorrect definitions can lead to unexpected unit conversions or a loss of the original unit information if the measurement is stored and retrieved without explicit handling for the custom units.
Install
-
pip install measurement
Imports
- Distance
from measurement.measures import Distance
- Weight
from measurement.measures import Weight
- Temperature
from measurement.measures import Temperature
- MeasureBase
from measurement.base import MeasureBase
Quickstart
from measurement.measures import Weight, Distance
# Create a Weight object
weight_1 = Weight(lb=125)
weight_2 = Weight(kg=40)
# Perform arithmetic operations
added_together = weight_1 + weight_2
print(f"Weight 1: {weight_1}")
print(f"Weight 2: {weight_2}")
print(f"Sum in pounds: {added_together.lb:.2f} lb")
print(f"Sum in kilograms: {added_together.kg:.2f} kg")
# Create a Distance object and convert units
distance_m = Distance(m=1000)
distance_km = distance_m.km
distance_miles = distance_m.miles
print(f"1000 meters is {distance_km:.2f} km")
print(f"1000 meters is {distance_miles:.2f} miles")