Search code examples
pythonpint

Parse just unit with pint


The pint docs are clear about how to parse a quantity like "1 meter". How do I parse just a unit, like "meter"? All of these return a quantity with a value of 1:

import pint
ureg = pint.UnitRegistry()

ureg('meter')  # Quantity 1 meter
ureg['meter']  # Quantity 1 meter
ureg.parse_expression('meter')  # Quantity 1 meter

I know that I can do quantity.u or quantity.units to get just the units, but that seems clunky.


Solution

  • Each registry has a Unit class that can be used to parse a string directly into a unit:

    import pint
    ureg = pint.UnitRegistry()
    
    ureg.Unit('m')  # Unit meter