initial work, basic unit class

This commit is contained in:
James Turk 2015-03-23 17:41:55 -04:00
commit 94af033fcd
4 changed files with 72 additions and 0 deletions

1
README.md Normal file
View File

@ -0,0 +1 @@
personification of force and pure energy

0
bia/__init__.py Normal file
View File

18
bia/test_units.py Normal file
View File

@ -0,0 +1,18 @@
from .units import Mass
def test_basic_conversions():
a = Mass(2, 'kg')
kg = a.as_unit('kg')
assert kg.scalar == 2
assert kg.unit == 'kg'
lb = a.as_unit('lb')
assert abs(lb.scalar - 4.40925) < 0.0001
assert lb.unit == 'lb'
g = a.as_unit('g')
assert abs(g.scalar - 2000) < 0.0001
assert g.unit == 'g'
assert g.as_unit('lb').scalar == a.as_unit('lb').scalar

53
bia/units.py Normal file
View File

@ -0,0 +1,53 @@
from collections import defaultdict
class UnitError(ValueError):
pass
class ConversionError(ValueError):
pass
class Unit(object):
_mapping = {}
def __init__(self, n, unit):
self.scalar = n
if unit not in self._mapping:
raise ValueError('invalid unit {} for {}'.format(unit, self.__class__.__name__))
self.unit = unit
def as_unit(self, unit):
if self.unit == unit:
return self.__class__(self.scalar, self.unit)
try:
if self.unit == self._base:
factor = self._mapping[unit]
else:
factor = self._mapping[unit] / self._mapping[self.unit]
except KeyError:
raise ConversionError('cannot convert from {} to {}'.format(self.unit, unit))
return self.__class__(self.scalar * factor, unit)
def __str__(self):
return '{}{}'.format(self.scalar, self.unit)
def __repr__(self):
return 'U({}, {!r})'.format(self.scalar, self.unit)
def __cmp__(self):
pass
class Mass(Unit):
_base = 'kg'
# 1kg ==
_mapping = {
'kg': 1.0,
'lb': 2.20462,
'g': 1000.0,
}