Search code examples
pythonpint

In pint, how do I redefine the micro- symbol to be µ-, not u-?


In pint, how do I redefine the micro- prefix to be spelt µ- rather than u-? Both are aliases when defining units, but when obtaining the short symbol such as with the {:~} format specification, pint reverts to u- even when I try to redefine micro- = 1e-6 = µ-:

In [155]: ureg.define("micro- = 1e-6 = µ-")
WARNING  2016-01-06 15:19:07,017 unit._adder:563: Redefining 'micro' (<class 'pint.definitions.PrefixDefinition'>)
WARNING  2016-01-06 15:19:07,017 unit._adder:563: Redefining 'µ' (<class 'pint.definitions.PrefixDefinition'>)

(Note that these warnings are apparently issued through the logging module and show up due to a rule in my .pythonrc, logging.basicConfig(format=("%(levelname)-8s %(asctime)s %(module)s.%(funcName)s:%(lineno)s: %(message)s"), level=logging.DEBUG))

In [156]: x = 3 * ureg.micrometre

In [157]: ureg._get_symbol("micrometer")
Out[157]: 'um'

In [158]: "{:~}".format(x)
Out[158]: '3 um'

How do I redefine the micro- entry in the registry such that "{:~}".format(x) will give me 3 µm rather than 3 um?

Edit

I'm using pint from the latest git repository:

In [161]: print(pint.__version__)
0.7.dev0

Edit 2

The situation appears to occur only if there exist previously defined quantities that use the u- prefix:

In [3]: ureg = pint.UnitRegistry()

In [4]: q = 12 * ureg.um

In [5]: ureg.define("micro- = 1e-6 = µ-")
WARNING  2016-01-06 15:41:25,477 unit._adder:563: Redefining 'micro' (<class 'pint.definitions.PrefixDefinition'>)
WARNING  2016-01-06 15:41:25,477 unit._adder:563: Redefining 'µ' (<class 'pint.definitions.PrefixDefinition'>)

In [6]: x = 3 * ureg.micrometre

In [7]: "{:~}".format(x)
Out[7]: '3 um'

But (new session):

In [7]: x = 3 * ureg.micrometre

In [8]: "{:~}".format(x)
Out[8]: '3 µm'

So I suppose redefining the default needs to be done before using the u- alias.


Solution

  • You need to redefine the µ- prefix before using the (admittedly convenient for somewhat easier to type) u- prefix:

    In [2]: ureg = pint.UnitRegistry()
    
    In [3]: ureg.define("micro- = 1e-6 = µ-")
    
    In [4]: x = 3 * ureg.um
    
    In [5]: print("{:~}".format(x))
    3 µm
    

    But (other session):

    In [3]: x = 3 * ureg.um
    
    In [4]: ureg.define("micro- = 1e-6 = µ-")
    
    In [5]: print("{:~}".format(x))
    3 um