Skip to content

Commit

Permalink
fix hash dict when using unhashable types (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
ldruschk authored May 23, 2021
1 parent 07fe549 commit 2d23680
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/enochecker/nosqldict.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
DB_DEFAULT_PORT = 27017


def value_to_hash(value: Any) -> int:
def value_to_hash(value: Any) -> Optional[int]:
"""
Create a stable hash for a value based on the json representation.
Expand All @@ -37,7 +37,10 @@ def value_to_hash(value: Any) -> int:
:param key: the value to hash
:return: hash in string format
"""
return hash(json.dumps(value, sort_keys=True))
try:
return hash(json.dumps(value, sort_keys=True))
except TypeError:
return None


def _try_n_times(func: Callable[..., Any]) -> Callable[..., Any]:
Expand Down Expand Up @@ -162,7 +165,9 @@ def __setitem__(self, key: str, value: Any) -> None:
key = str(key)

self.cache[key] = value
self.hash_cache[key] = value_to_hash(value)
hash_ = value_to_hash(value)
if hash_:
self.hash_cache[key] = hash_

self._upsert(key, value)

Expand Down Expand Up @@ -210,7 +215,9 @@ def __getitem__(self, key: str, print_result: bool = False) -> Any:

if result:
self.cache[key] = result["value"]
self.hash_cache[key] = value_to_hash(result)
hash_ = value_to_hash(result)
if hash_:
self.hash_cache[key] = hash_
return result["value"]
raise KeyError("Could not find {} in {}".format(key, self))

Expand Down Expand Up @@ -262,7 +269,11 @@ def persist(self) -> None:
"""
for (key, value) in self.cache.items():
hash_ = value_to_hash(value)
if self.hash_cache[key] != hash_:
if (
(not hash_)
or (key not in self.hash_cache)
or (self.hash_cache[key] != hash_)
):
self._upsert(key, value)

def __del__(self) -> None:
Expand Down

0 comments on commit 2d23680

Please sign in to comment.