Skip to content
Snippets Groups Projects
Commit 4335728d authored by Markus Scheidgen's avatar Markus Scheidgen
Browse files

Added unit cache in front of pint registry.

parent 4371e71e
No related branches found
No related tags found
No related merge requests found
......@@ -15,7 +15,18 @@ from pint import UnitRegistry
logger = logging.getLogger(__name__)
# disable warnings from pint
logging.getLogger("pint").setLevel(logging.ERROR)
ureg = UnitRegistry(os.path.join(os.path.dirname(__file__), "units.txt"))
_ureg_cache = dict()
def ureg_cached(unit):
if unit in _ureg_cache:
return _ureg_cache[unit]
else:
unit_def = ureg(unit)
_ureg_cache[unit] = unit_def
return unit_def
#===============================================================================
......@@ -51,7 +62,7 @@ def convert_unit(value, unit, target_unit=None):
"""
# Check that the unit is valid
unit_def = ureg(unit)
unit_def = ureg_cached(unit)
if not unit_def:
logger.error("Undefined unit given. Cannot do the conversion")
return
......@@ -64,7 +75,7 @@ def convert_unit(value, unit, target_unit=None):
return converted_value.magnitude
else:
# Check that the given target unit is valid
target_unit_def = ureg(target_unit)
target_unit_def = ureg_cached(target_unit)
if not target_unit_def:
logger.error("Undefined target unit given. Cannot do the conversion")
return
......@@ -95,9 +106,9 @@ def convert_unit_function_immediate(unit, target_unit=None):
"""
# Check that the dimensionality of the source and target units match.
if target_unit is not None:
source = ureg(target_unit)
source = ureg_cached(target_unit)
source_dim = source.dimensionality
target = ureg(unit)
target = ureg_cached(unit)
target_dim = target.dimensionality
if source_dim != target_dim:
raise Exception("The dimensionality of unit '{}' does not match the dimensionality of unit '{}'. Cannot do the unit conversion.".format(unit, target_unit))
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment