How to override predefined unit in pint?

66 Views Asked by At

I use the pint library in my lab assignments to efficiently deal with unit specifications and conversions. We recently had an experiment when we took some pictures and in the code, we need to convert from pixels to meters with a conversion factor. I wanted to make a new pint unit for pixels so it handles this conversion automatically:

from pint import UnitRegistry

ureg = UnitRegistry(system="SI")
ureg.define("pixel = 5.2e-6 * meter = px")

size = 42 * ureg.pixel
print(size.to(ureg.meter))

Unfortunately, this code snippet doesn't work because pixel is already defined with the dimensionality of [printing_unit] so the conversion failed, and the alias px I tried to give it is already an alias for css_pixel which has a dimensionality of [length], but with a different conversion factor, so if write size = 42 * ureg.px, I don't get an error, but the conversion is wrong.

How can I override these default units with my definitions? I don't believe I'll ever use the predefined pixel or css_pixel units so I have no issue overriding them with units that are more specific to my code. I know I can use a definition file, but it seems to me like an overkill for such a simple task. This is a script for a physics lab assignment, so I don't want to make it very complicated.

0

There are 0 best solutions below