Skip to content
Advertisement

Pint: How do I define my own units in the Pint Python library?

I am working with Pint to do unit conversions in a Python project. The project involves temperature gradients, which are not defined in Pint. My units are typically “deg.C/km” so I’d like to be able to declare a Quantity as “55 deg.C/km”. I’d then like to use Pint to painlessly convert that Quantity to “XXX deg.F/mile” or “YYY deg.F/km” etc. This involves defining my own units using the built-in functionality of Pint, but I can’t figure that out.

For example, I’d like to be able to do this:

from pint import UnitRegistry, Quantity
ureg = UnitRegistry()
ureg.load_definitions('GEOPHIRES3_newunits.txt') 

Myquanity = Quantity("55 deg.C/km")
Myquantity_new_units = Myquanity.to("deg.F/mile")
Myquantity_new_units2 = Myquanity.to("deg.C/mile")

I should be able to do that by editing my own definitions file (defined as GEOPHIRES3_newunits.txt in the 3rd line of the code). This is what I have:

#Gradient
[gradient] = [temperature] / [length]
CooperC = degC/km = deg.C/km
CooperF = CooperC * 1.60934 * 1.7999 = degF/mi = deg.F/mi

Since “deg.C/km” is defined as an alias, it should work, but instead, it creates a Quantity of the wrong type – it creates <Quantity(55.0, ‘coulomb * degree / kilometer’)>.

Advertisement

Answer

From my first glance at Pint, I can spot a couple of issues in your code:

  1. You haven’t defined “deg.C/km” as an alias: “If one wants to specify aliases but not a symbol, the symbol should be conventionally set to _”
  2. I haven’t found anything in Pint docs (not that I was too keen), but it looks to me that dots are not allowed in unit aliases and symbols, they are treated as multiplication (hence “coulomb * degree” for deg.C in your error and “farad * degree” for deg.Fin my tests)
  3. Also your temperature gradient should not use absolute temperatures, but instead their delta counterparts, see Temperature conversion.
  4. Do you really need custom definitions for your units? From what I can see, “delta_degC/km” and “delta_degF/mile” are handled by Pint just fine with default unit registry.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement