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:
- 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 _”
- 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” fordeg.F
in my tests) - Also your temperature gradient should not use absolute temperatures, but instead their delta counterparts, see Temperature conversion.
- 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.