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

Viewed 167

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?

2 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

Inline comments are certainly acceptable in Python, but I'm not sure there is a single accepted way for annotating units. You might want to attach the information to the variable name, e.g. length_mm = 28. Or build a proper class or namedtuple, e.g.

>>> from collections import namedtuple
>>> Length = namedtuple('Length', ['value', 'unit'])
>>> ln = Length(28, 'mm')
>>> ln
Length(value=28, unit='mm')
>>> ln.value
28
>>> ln.unit
'mm'
Related