Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convention for indicating a quantity's units in Python code?

Please note that I'm coming at this from the point of view of human readability rather than informing the program itself of the units in use.


I'm working on a project at the moment with strong links to mechanical engineering, and one of the issues that has come up a couple of times is that it's not clear from my code what units a given quantity - usually a constant, but the criticism could be extended to some variables as well - is measured in.

At the moment, I'm doing this:

length = 28
# ^^^ measured in mm ^^^

But this feels hacky and a bit ugly. I could do this:

length = 28 # <<< measured in mm

That looks better, but I had it drummed into me at university that inline comments are Satanic, and it's a prejudice I'm having trouble letting go of. (Although, having said that, I was only taught C and Java in university, where the pitfalls of inline comments are more obvious. Are inline comments acceptable in Python?)

Is there some useful convention dictating how to indicate a quantity's units in a clear and elegant fashion? Or am I on my own on this one?

like image 399
Tom Hosker Avatar asked Sep 08 '20 08:09

Tom Hosker


People also ask

How do you write units in Python?

To assign a unit to a quantity, multiply by the unit, e.g. my_length = 100 * mm. (In normal text you would write “100 mm”, but unfortunately Python does not have “implied multiplication”.)

Which symbol is used for representing equality in Python?

Answer: In python, symbol '==' is used as equal to operator. It returns True if the values on its left and right side are equal, False otherwise.


1 Answers

On top of inline comments which are fine;

Option 1 : Variable name

You can set a variable name, yet it may fault if you calculate and change it later - so it better suits constants.

LENGTH_IN_METERS = 3

Option 2: pint

Pint is a nice library that lets you keep up with the variable measurement unit.

e.g.

import pint
ureg = pint.UnitRegistry()
3 * ureg.meter + 4 * ureg.cm
<Quantity(3.04, 'meter')>

Option 3: python-measurement

Easily use and manipulate unit-aware measurement objects in Python.

e.g.

Converting other measures into kilometers:

from measurement.measures import Distance
distance = Distance(mi=10).km
like image 152
Aviv Yaniv Avatar answered Oct 11 '22 06:10

Aviv Yaniv