Search code examples
pythonrepresentationpint

Python Pint: set short representation of units as default


Pint units are represented by default with their full name:

>>> import pint
>>> ureg = pint.UnitRegistry()
>>> q = ureg.Quantity('3.456 m^2')
>>> print(q)
3.456 meter ** 2
>>> print('The pretty representation is {:P}'.format(q))
The pretty representation is 3.456 meter²

From the docs and from this answer it comes out that units can be represented in their short form, which is the way they are commonly represented in the real world:

>>> print(format(q,'~'))
3.456 m ** 2
>>> print('The pretty representation is {:~P}'.format(q))
The pretty representation is 3.456 m²

However, I would like to set the short representation as default, is it possible?


Solution

  • I found this at the bottom of this section String formatting in the tutorial. This is a minimal working example:

    import pint
    
    ureg = pint.UnitRegistry()
    ureg.default_format = '~' # Add this if you want to use abbreviated unit names.
    accel = 1.3 * ureg['meter/second**2']
    print(f'The acceleration is {accel}')
    

    This outputs: The acceleration is 1.3 m / s ** 2

    These are also valid options for short units: ~L (LaTeX), ~H (HTML) and ~P (Pretty print).