Search code examples
pythonunits-of-measurementpint

Check dimensionality of complex unit in pint


I am trying to check for dimensionality of a unit that is complex such as volume (m^3) or velocity (ft/min). How can I use the "pint.check()" method to see if a quantity is of that type of dimension?

This is what I have tried:

import pint
ureg = pint.UnitRegistry()

volume = 4.3 * ureg.gal

Doing this makes sense:

volume.dimensionality
Out[3]: <UnitsContainer({'[length]': 3.0})>

So I tried the "check" function but I don't know how to do it for volume:

volume.check('[length]', 3)

Unfortunately, this doesn't work:

Traceback (most recent call last):
  File "C:\Users\jle\...\interactiveshell.py", line 3291, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-4722a8cb0b0c>", line 1, in <module>
    volume.check('[length]', 3)
TypeError: check() takes 2 positional arguments but 3 were given

Solution

  • You can check for volume using check('[volume]'):

    import pint
    ureg = pint.UnitRegistry()
    
    volume = 4.3 * ureg.gal
    
    # Returns True
    volume.check('[volume]')
    

    You can check for velocity using check('[length]/[time]'):

    velocity = 1 * ureg.feet / ureg.second
    
    # Returns True
    velocity.check('[length]/[time]')