Back to main.

Calmcode Shorts

pint.py logopint.py

In some countries length is measured in feet while in other countries it is measured in meters. If you're going to translate these units you want to be careful though, because a mere typo might ruin everything. That's why it might be better to use a package like pint.

You can pip install it via:

pip install pint

Once installed, you can start using the unit registry inside of pint.

import pint
ureg = pint.UnitRegistry()

This unit registry is the main object that you'll interact with. It allows you to define quantities that have a magnitude and a unit attached. For example, you can add meters and centimeters together by just using arithmetic.

3 * ureg.meter + 4 * ureg.cm
# 3.04 meter

The result of 3 * ureg.meter + 4 * ureg.cm is itself an object that can be used to translate the quantity to another unit.

(3 * ureg.meter + 4 * ureg.cm).to(ureg.feet)
# 9.9737 foot

Pint also allows you to create units dynamically. Speed, for example, is defined by distance divided by time.

60 * ureg.miles / ureg.hour
# 60.0 mile/hour

You can translate this to meters per minute, just like before!

(60 * ureg.miles / ureg.hour).to(ureg.meters/ureg.minute)
# 1609.344 meter/minute

You can also use strings to define units. If you'd like. Sometimes this is more convenient.

ureg("meter/second**2") * 10 * ureg("seconds")
# 10.0 meter/second

A final thing that's worth pointing out is that you can also define your own units.

ureg.define("dog_year = 52 * day = dy")
(5 * ureg("years").to(ureg("dog_year")))
# 35.1201 dog_year

There are lots of units available in the library so certainly feel free to explore. The final thing that's worth pointing out is that you can also fetch the properies of a quantity via;

(60 * ureg.miles / ureg.hour).magnitude
# 60.0
(60 * ureg.miles / ureg.hour).units
# mile/hour
(60 * ureg.miles / ureg.hour).dimensionality
# <UnitsContainer({'[length]': 1, '[time]': -1})>

Back to main.