Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse just unit with pint

Tags:

python

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.

like image 449
drhagen Avatar asked Apr 14 '26 23:04

drhagen


1 Answers

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
like image 122
drhagen Avatar answered Apr 16 '26 12:04

drhagen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!