0

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?

  • You said the Pint docs aren't very clear on how to define a unit -- did you read the section on "defining units"? https://pint.readthedocs.io/en/stable/defining.html – Samwise Jul 30 '22 at 15:55

1 Answers1

2

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'
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • That worked. Thanks very much. I read the docs several times but just didn't get it. – Barry Andersen Jul 30 '22 at 15:59
  • I'm new to `pint`, but it looks like you can do `ureg.define('USD = [currency]')` to define `currency` as a new base dimension that will work in things like `5 * ureg('USD / kWh')`. – Ken Williams Jan 06 '23 at 20:29