Format Pint unit as short-form symbol

Viewed 599

Say I have an arbitrary Pint quantity q. Is there a way to display its units in symbol short form, instead of as a full-length word?

In other words, how would I code unit_symbol() such that it returns "m", not "meter"; "kg" not "kilogram"; etc.? Is there a way to retrieve the short-form unit symbol that is synonym with the quantity's current unit?

import pint 
ureg = pint.UnitRegistry()
Q_ = ureg.Quantity

def unit_symbol(q: pint.Quantity) -> str:
    # Intended to return "m", not "meter"
    # "kg" not "kilogram"
    # etc.
    # ???
    return q.units  # returns long-form unit, "meter", "kilogram" etc. :-(
    
q = Q_(42, ureg.m)
print(unit_symbol(q))  # "meter"... whereas I would like "m"

The above obviously fails to achieve this; it returns the long-form unit.

3 Answers

You can use '~' as a spec for the unit formatting:

q = Q_(42, "m") / Q_(1, "second")

print(format(q, '~'))  # 42.0 m / s
print(format(q.u, '~'))  # m / s

This feature is apparently undocumented, but can be inferred from the source code for Unit.__format__ (search for "~" on that page to quickly navigate to the relevant piece of code).

I found UnitRegistry.get_symbol(),

ureg.get_symbol(str(q.units))  # "m"

but it seems a bit clunky: converting unit to string, then parsing that string again...

Also this fails for composite units e.g.

q = Q_(42, "m") / Q_(1, "second")
ureg.get_symbol(str(q.units))  
# UndefinedUnitError: 'meter / second' is not defined in the unit registry

Use ureg.default_format = '~' if you want the short notation by default. These are also valid options for short units: ~L (LaTeX), ~H (HTML) and ~P (Pretty print).

Related