How are currency units used with Python Pint units?

Question:

I would like to do something like this:

import pint
ureg = pint.UnitRegistry()

kg = ureg.kg
USD = ureg.USD  # not the way to do this

weight = 2.3 * kg
price = 1.49 * USD / kg
cost = weight * price
print(f"{cost:~.2f}")

>>> 3.43 USD

The Pint docs including the tutorial are not very clear on this.

The error I get with this code is:

pint.errors.UndefinedUnitError: ‘USD’ is not defined in the unit registry

So, how do I define USD in the unit registry?

Asked By: Barry Andersen

||

Answers:

Use ureg.define() to define a new unit. There is no "currency" dimension in the default registry, but you can just add one at the same time you define your unit.

import pint
ureg = pint.UnitRegistry()

ureg.define('USD = currency')

kg = ureg.kg
USD = ureg.USD

weight = 2.3 * kg
price = 1.49 * USD / kg
cost = weight * price
print(f"{cost:~.2f}")  # prints '3.43 USD'
Answered By: Samwise