Unitconvert Python Module

Table of Contents
  1. Background
  2. How It Works
  3. Installing as a Python Module
  4. Examples
  5. Download

Background

In one of my CS courses, we had to code our own interpreter for a given language specification. After the lectures on BNF, lexers, and parsers, I decided to get some practice with a personal project.

I decided to write a simple, proof-of-concept unit converter in Python, which would be able to convert between different metric units, and even U.S. customary units. The unit converter also performs basic arithmetic operations on numbers, converting any units as necessary.

How It Works

The unit converter works by expressing each measurement by a value and a list of the seven base SI units: kg, m, s, K, A, mol, and cd.

For example, numbers would be represented by something like:

12 N
{
	"magnitude": 12,
	"units": {
		"kg": 1,
		"m": 1,
		"s": -2,
		"K": 0,
		"A": 0,
		"mol": 0,
		"cd": 0
	}
}
83 cm/s
{
	"magnitude": 0.83,
	"units": {
		"kg": 0,
		"m": 1,
		"s": -1,
		"K": 0,
		"A": 0,
		"mol": 0,
		"cd": 0
	}
}

The tables used to convert between units look like this:

Metric Units

Metric units (click to enlarge)

Customary Units

Customary units (click to enlarge)

Notice how the customary system has a lot of units for each base SI unit, and none of the scales are at all nice to work with (all the scales are used to convert to metric equivalent bases). This table is what allows us to convert between systems and units, and perform basic arithmetic operations on them. By storing everything in base SI units, it becomes easier to add, multiply, convert, etc. between different units and systems.

Installing as a Python Module

To install the module for importing into other scripts, you can put the files in a directory called unitconvert in one of these paths:

~/.local/lib/python3.6/site-packages/
/usr/local/lib/python3.6/dist-packages/
/usr/lib/python3/dist-packages/

To import it into a script:

from unitconvert.number import Number
from unitconvert.parser import Parser

num = Number("74 m/s")

Examples

Examples can be found here on GitHub.

Download

unitconvert can be downloaded on GitHub.