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?
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”.)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With