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 00187e9 commit 39f2117
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 11 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
13 changes: 3 additions & 10 deletions pint/facets/plain/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,13 @@ 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
attrs = (
"dimensional_equivalents",
"root_units",
"dimensionality",
"parse_unit",
)
return all(getattr(self, attr) == getattr(other, attr) for attr in attrs)

Expand Down Expand Up @@ -589,6 +585,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 +1162,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 +1173,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 +1203,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 39f2117

Please sign in to comment.