pint icon indicating copy to clipboard operation
pint copied to clipboard

Currency symbols $ € £ cannot be used

Open scanzy opened this issue 1 year ago • 3 comments

Hello, I am trying to add currency units, using symbols $, , £ but the units get mapped to dimensionless.

import pint
ureg = pint.UnitRegistry()
ureg.define("euro = [currency] = € = EUR")

print(ureg.Quantity("1 €"))
# I get "1 dimensionless", just as € was ignored
# It's the same using $ or £, or other symbols like ! and &

In fact, I get the same behaviour even without defining the unit euro.

import pint
ureg = pint.UnitRegistry()

print(ureg.Quantity("1 €"))
# I get "1 dimensionless", just as € was ignored, like before

I believe special chars like €$£& are ignored. Is this a bug? Thank you a lot

scanzy avatar Jul 06 '23 12:07 scanzy

I dealt with currency symbols this way: https://github.com/hgrecco/pint/issues/1687

MichaelTiemannOSC avatar Jul 11 '23 09:07 MichaelTiemannOSC

Thank you @MichaelTiemannOSC for your response! Actually I could not fully understand your code but I got my example to work using a preprocessor.

import pint
ureg = pint.UnitRegistry(preprocessors = [lambda s: s.replace("€", "EUR")])
ureg.define("euro = [currency] = € = EUR")

print(ureg.Quantity("1 €"))
# I get "1 euro", it works!

It seems to me more like a hack (bug workaround) than a solution, so I hope someone could figure out something different.

scanzy avatar Jul 12 '23 12:07 scanzy

There are three levels of conversions pint does:

  1. Purely implicit (you don't need to ask, and applies everywhere)
  2. Explicit (you use .to() or .m_as())
  3. Manual (you write the code for how you want the registry to work), and it applies to that registry everywhere

You give a good example of case 3. The patch I wrote applies to case 2 (affects all registries, but only in the case of explicit conversions). Maybe a better way to write the patch would be to combine the two so users can control explicit conversions on a per-registry basis. @hgrecco your thoughts?

MichaelTiemannOSC avatar Jul 12 '23 12:07 MichaelTiemannOSC