aboutsummaryrefslogtreecommitdiff
path: root/src/ee/__init__.py
diff options
context:
space:
mode:
authorTrygve Laugstøl <trygvis@inamo.no>2019-05-23 21:08:36 +0200
committerTrygve Laugstøl <trygvis@inamo.no>2019-05-26 21:55:41 +0200
commit1699cca793c6a8ebc00942557b6764fff6739044 (patch)
treeee8162390db5a7607298fe5f40841bb131b60542 /src/ee/__init__.py
parent4afac7dc4c743284e5243428f00928aa7eaacfdc (diff)
downloadee-python-1699cca793c6a8ebc00942557b6764fff6739044.tar.gz
ee-python-1699cca793c6a8ebc00942557b6764fff6739044.tar.bz2
ee-python-1699cca793c6a8ebc00942557b6764fff6739044.tar.xz
ee-python-1699cca793c6a8ebc00942557b6764fff6739044.zip
part-find-requirements: wip
Diffstat (limited to 'src/ee/__init__.py')
-rw-r--r--src/ee/__init__.py26
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