Skip to content

Commit

Permalink
Migrate parse_units to functools.cache
Browse files Browse the repository at this point in the history
  • Loading branch information
hgrecco committed Jul 15, 2023
1 parent 7979d07 commit 1127585
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 10 deletions.
1 change: 0 additions & 1 deletion pint/facets/context/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ def __init__(self, registry_cache: RegistryCache) -> None:
self.dimensional_equivalents = registry_cache.dimensional_equivalents
self.root_units = {}
self.dimensionality = registry_cache.dimensionality
self.parse_unit = registry_cache.parse_unit


class GenericContextRegistry(
Expand Down
12 changes: 3 additions & 9 deletions pint/facets/plain/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,6 @@ def __init__(self) -> None:
#: Maps dimensionality (UnitsContainer) to Units (UnitsContainer)
self.dimensionality: dict[UnitsContainer, UnitsContainer] = {}

#: Cache the unit name associated to user input. ('mV' -> 'millivolt')
self.parse_unit: dict[str, UnitsContainer] = {}

def __eq__(self, other: Any):
if not isinstance(other, self.__class__):
return False
Expand Down Expand Up @@ -589,6 +586,8 @@ def _build_cache(self, loaded_files=None) -> None:
return

self._cache = RegistryCache()
for func in (self._parse_single_unit, self._parse_units):
func.cache_clear()

deps: dict[str, set[str]] = {
name: set(definition.reference.keys()) if definition.reference else set()
Expand Down Expand Up @@ -1164,6 +1163,7 @@ def parse_units(
units = self._parse_units(input_string, as_delta, case_sensitive)
return self.Unit(units)

@functools.cache
def _parse_units(
self,
input_string: str,
Expand All @@ -1174,12 +1174,9 @@ def _parse_units(
the canonical names.
"""

cache = self._cache.parse_unit
# Issue #1097: it is possible, when a unit was defined while a different context
# was active, that the unit is in self._cache.parse_unit but not in self._units.
# If this is the case, force self._units to be repopulated.
if as_delta and input_string in cache and input_string in self._units:
return cache[input_string]

for p in self.preprocessors:
input_string = p(input_string)
Expand Down Expand Up @@ -1207,9 +1204,6 @@ def _parse_units(
cname = "delta_" + cname
ret = ret.add(cname, value)

if as_delta:
cache[input_string] = ret

return ret

def _eval_token(
Expand Down

0 comments on commit 1127585

Please sign in to comment.