GitHunt
KU

kurtbrose/python-units

SymPy.physics.units is a better implementation of this functionality; recommend using that module

from units import *

Units are represented by classes. For example, meter, kilogram, and second
are all classes in the units module. Like int and str, instances of these classes
are immutable.

Arithmetic on units returns other units of the appropriate class.

m*m
<class 'units.*m**2'>

The units library understands the difference between base units and derived
units, and is a little bit smart about how it treats them.

kgm/s**2
<class 'units.Newton'>
N
m
<class 'units.Joule'>
J/s
<class 'units.Watt'>

Multiplying a unit times anything will result in an instance of that unit, holding
onto the value.

5m
5
m

Multiplying that instance by something else will multiply the value.

5m2.5
12.5*m

Multiplying two unit instances together will multiply their values and classes.

meter(5)2
25*meter
2

Addition and subtraction between incompatible units causes an exception to be thrown.

1s + 1m
Traceback (most recent call last):
File "", line 1, in
File "units.py", line 89, in add
raise TypeError() #figure out good error message
TypeError

The library 'plays nice' with many other libraries, since it doesn't require any
specific type for the values it is wrapping. Anything that supports the arithmetic
operators will do.

Here is an example of combining python-units with the SymPy library to do symbolic math
with physical units:

import sympy
import units
x = sympy.Symbol('x')
y = sympy.Symbol('y')
xunits.meter
x
m
xunits.meter + yunits.meter
x + y*m

And here is an example of combining python-units with the NumPy library to do fast
numerical computation with units:

import numpy
a = numpy.array([[1,2],[3,4]])
a
array([[1, 2],
[3, 4]])
am = a*units.meter
am
array([[1, 2],
[3, 4]])m
am
2/units.meter
array([[2,4],
[6,8]])

Instances of units are pickle-able, although the unit classes themselves are not.
(Pending issue 7689 being fixed http://bugs.python.org/issue7689).

import pickle
pickle.loads(pickle.dumps(3mm))
3*m**2

Unitless values get unwrapped. That is, an expression that would result in a unitless
value instead just returns the value.

L = 5 * units.meter
L
5*m
L / units.meter
5

This is for use cases such as applying trigonometric functions to values. In general,
it is only physically valid to pass unitless numbers to arbitrary functions.

((Note: still iffy on this -- is it better to return an instance of Unitless for consistency?))

Languages

Python100.0%

Contributors

Created January 2, 2011
Updated March 15, 2019