diff options
Diffstat (limited to 'src/ee/__init__.py')
-rw-r--r-- | src/ee/__init__.py | 26 |
1 files changed, 22 insertions, 4 deletions
diff --git a/src/ee/__init__.py b/src/ee/__init__.py index 2ba113e..06c5aab 100644 --- a/src/ee/__init__.py +++ b/src/ee/__init__.py @@ -1,5 +1,6 @@ import re from functools import total_ordering +from typing import Optional import math @@ -52,8 +53,10 @@ class EeVal(object): 'P': 15, 'E': 18, } + keys = "".join(exponents.keys()) + units = "|".join(units) r = re.compile( - "([0-9]+\\.[0-9]+|\\.?[0-9]+|[0-9]+\\.?) *([" + "".join(exponents.keys()) + "]?) *(" + "|".join(units) + "?)") + "([0-9]+(?:\\.[0-9]*)?(?:e-?[0-9]+)|[0-9]+\\.[0-9]+|\\.?[0-9]+|[0-9]+\\.?) *([" + keys + "]?) *(" + units + "?)") def __init__(self, s=None, value=None, exp=None, unit=None): # This is where I regret having a string in the API at once. @@ -66,7 +69,14 @@ class EeVal(object): (self._value, self._exp, self._unit) = (value, exp, unit) @staticmethod - def parse(s) -> "EeVal": + def try_parse(s, expected_unit=None) -> Optional["EeVal"]: + try: + return EeVal.parse(s, expected_unit) + except EeException: + return None + + @staticmethod + def parse(s, expected_unit=None) -> "EeVal": m = EeVal.r.match(s) if not m: raise EeException("Could not parse value: " + str(s)) @@ -79,10 +89,18 @@ class EeVal(object): e = math.ceil(math.log10(value)) exp = exp + e value = value * math.pow(10, -e) - return EeVal(None, value=float(value), exp=exp, unit=unit if len(unit) > 0 else None) + + unit = unit if len(unit) > 0 else None + if expected_unit is not None: + if unit is None: + unit = expected_unit + elif unit != expected_unit: + raise EeException("Bad unit when parsing, expected {}, got {}".format(expected_unit, unit)) + + return EeVal(None, value=float(value), exp=exp, unit=unit) @property - def value(self): + def value(self) -> float: return self.__float__() @property |