From 867852503157299b67fe05645aea11b9da0f2a84 Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Wed, 20 Dec 2017 15:23:41 +0100 Subject: o Making a setter for EeVal that returns a new EeVal. --- src/ee/__init__.py | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) (limited to 'src/ee/__init__.py') diff --git a/src/ee/__init__.py b/src/ee/__init__.py index 2fad46d..7f228f8 100644 --- a/src/ee/__init__.py +++ b/src/ee/__init__.py @@ -18,7 +18,9 @@ class EeException(Exception): @total_ordering class EeVal(object): from decimal import Decimal - units = ['F', 'Ohm', '\u2126', 'H'] + units = ['F', + 'Ohm', '\u2126', # Ohm symbol + 'H'] exponents = { 'f': -15, 'p': -12, @@ -37,7 +39,18 @@ class EeVal(object): r = re.compile( "([0-9]+\\.[0-9]+|\\.?[0-9]+|[0-9]+\\.?) *([" + "".join(exponents.keys()) + "]?) *(" + "|".join(units) + "?)") - def __init__(self, s): + def __init__(self, s, value=None, exp=None, unit=None): + # This is where I regret having a string in the API at once. + if s: + val = EeVal.parse(s) + (self._value, self._exp, self._unit) = (val._value, val._exp, val._unit) + else: + if value is None or exp is None: + raise EeException("Bad arguments, value and exp has to be set.") + (self._value, self._exp, self._unit) = (value, exp, unit) + + @staticmethod + def parse(s) -> "EeVal": m = EeVal.r.match(s) if not m: raise EeException("Could not parse value: " + str(s)) @@ -50,9 +63,7 @@ class EeVal(object): e = math.ceil(math.log10(value)) exp = exp + e value = value * math.pow(10, -e) - self._value = float(value) - self._exp = exp - self._unit = unit if len(unit) > 0 else None + return EeVal(None, value = float(value), exp = exp, unit = unit if len(unit) > 0 else None) @property def value(self): @@ -62,11 +73,17 @@ class EeVal(object): def unit(self): return self._unit + def set(self, value=None, exp=None, unit=None): + return EeVal(None, + value=value if value else self._value, + exp=exp if exp else self._exp, + unit=unit if unit else self._unit) + def __hash__(self): return hash((self.__float__(), self._unit)) def __eq__(self, other): - return ((self.__float__(), self._unit) == (other.__float__(), other._unit)) + return math.isclose(self.__float__(), other.__float__()) and self._unit == other._unit def __lt__(self, other): return ((self.__float__(), self._unit) < (other.__float__(), other._unit)) -- cgit v1.2.3