unitmeasure is a simple Python library that tries to implement the features of Swift's Units and Measurement framework.
With unitmeasure, you can label numeric quantities with physical dimensions and convert between related units.
For anyone looking to contribute, you can look at doing any of the following:
- Submit bugs and feature requests
- Review any documentation and create pull requests for anything from typos to new content.
unitmeasure can be installed from PyPI:
pip install unitmeasure
The basic available classes should match the classes found in swift.
Unit- represents a unit that has asymbolto describe it.Dimension- subclass ofUnitand has multiple child classes defining different dimensions.Measurement- Immutable. wraps a number with a unit. Supports comparison operators, addition and subtraction with another measurement, and multiplication and division with a scalar value.
All supported units can be found in the units sub directory. Any unit class can be imported directly from unitmeasure.
for more detailed usage see unit tests.
import unitmeasure
dur = unitmeasure.Measurement(value=2,
unit=unitmeasure.UnitDuration.minutes)
print(dur)import unitmeasure
dur = unitmeasure.Measurement(value=2,
unit=unitmeasure.UnitDuration.minutes)
dur.convert(unitmeasure.UnitDuration.seconds)
print(dur)import unitmeasure
minutes = unitmeasure.Measurement(value=2,
unit=unitmeasure.UnitDuration.minutes)
seconds = minutes.converted(unitmeasure.UnitDuration.seconds)
print(minutes)
print(seconds)import unitmeasure
minutes = unitmeasure.Measurement(value=2,
unit=unitmeasure.UnitDuration.minutes)
seconds = minutes.converted(unitmeasure.UnitDuration.seconds)
# adding measurements will automagically convert the measurement into its base unit.
print(minutes + seconds)import unitmeasure
customLengthUnit = unitmeasure.UnitLength(symbol="FLARB", coefficient=2.0)
customLength = Measurement(value=1, unit=customLengthUnit)
meters = customLength.converted(to: unitmeasure.UnitLength.meters)NOTE: JSON struct should match swift's so it should be possible to import json data to/from swift.
import unitmeasure
seconds = unitmeasure.Measurement(value=2,
unit=unitmeasure.UnitDuration.seconds)
with open("measurement.json", "w") as f:
f.write(unitmeasure.to_json(seconds))
with open("measurement.json", "r") as f:
# if a dimension is not specified you will end up with
# a measurement that has a basic unit (only a symbol)
loaded_measurement = unitmeasure.from_json(f.read(), dimension=unitmeasure.UnitDuration)