commit 94af033fcde522937733b1b04de2abacb255414e Author: James Turk Date: Mon Mar 23 17:41:55 2015 -0400 initial work, basic unit class diff --git a/README.md b/README.md new file mode 100644 index 0000000..ac2f31f --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +personification of force and pure energy diff --git a/bia/__init__.py b/bia/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bia/test_units.py b/bia/test_units.py new file mode 100644 index 0000000..321bcbe --- /dev/null +++ b/bia/test_units.py @@ -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 diff --git a/bia/units.py b/bia/units.py new file mode 100644 index 0000000..77f395a --- /dev/null +++ b/bia/units.py @@ -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, + }