I tried many of the Python Units packages available when I started adding physical quantities (magnitude and units) support to Lantz. There are really great packages out there providing NumPy support and a broad definition list including units and constants.
However these packages define the units within the Python code. This results in an unnecessary large and difficult to maintain package. Additionally, translation to other languages and changing to an incompatible system (eg. from SI to Gaussian) is impossible without changing the codebase.
Pint is a units package for Python that keeps the definitions in a separate text file. The text file is really easy to read and modify, allowing you to update the unit definitions without changing the code. For each unit, you just type the relation with other units. Aliases can be added after the second equal. For example, here are the definitions of hour an minute:
hour = 60 * minute = h = hrIt is very natural. Prefixes are also defined in the text file using a dash after them:
minute = 60 * second = min
yocto- = 10.0**-24 = y-It is worth noting that this is not a Python file that is evaluated but a text file that is parsed. The same is true for the units in your program. Therefore:
- Simple plural forms are automatically recognized. Once that you have defined meter, you don't need to define meters.
- All combinations of prefix + unit + singular/plural are recognized. Once that have you defined kilo and meter, you don't need to define kilometer nor kilometers.
The Quantity class contains two important attributes: magnitude and units. The magnitude can be any numeric type (int, float, decimal, fraction and even NumPy arrays). Mathematical operations between two magnitudes will be dispatched to the underlying types. In addition, ufuncs and ndarray methods are supported proving excellent NumPy integration.
A few other nice features:
- A comprehensive default unit definition file (SI, English language)
- Advanced string formatting: a quantity can be formatted into string using PEP 3101 syntax. Extended conversion flags are given to provide latex and pretty formatting.
- You instantiate and populate the unit registry. You can use the default unit definition file or your own (replacing or appending).
- Small and maintainable code base.
- Python 2.7 and 3.X in a single codebase.
- Full test coverage.
Read the docs: https://pint.readthedocs.org/
or fork the code: https://github.com/hgrecco/pint