Skip to content

Commit

Permalink
cleanups, add mock test
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Jan 16, 2025
1 parent 63e0455 commit dbe4e5f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
7 changes: 4 additions & 3 deletions pytools/persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,14 +331,15 @@ def update_for_specific_dtype(self, key_hash: Hash, key: Any) -> None:

def update_for_numpy_scalar(self, key_hash: Hash, key: Any) -> None:
import numpy as np
if IS_BIGENDIAN:
key = key.byteswap()
if hasattr(np, "complex256") and key.dtype == np.dtype("complex256"):
key_hash.update(repr(complex(key)).encode("utf8"))
elif hasattr(np, "float128") and key.dtype == np.dtype("float128"):
key_hash.update(repr(float(key)).encode("utf8"))
else:
key_hash.update(np.array(key).tobytes())
if IS_BIGENDIAN:
key_hash.update(np.array(key).byteswap().tobytes())
else:
key_hash.update(np.array(key).tobytes())

def update_for_dataclass(self, key_hash: Hash, key: Any) -> None:
self.rec(key_hash, f"{type(key).__qualname__}.{type(key).__name__}")
Expand Down
13 changes: 13 additions & 0 deletions pytools/test/test_persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,19 @@ def test_scalar_hashing() -> None:
assert keyb(np.complex256(1.1+2.2j)) == keyb(np.complex256(1.1+2.2j))
assert keyb(np.clongdouble(1.1+2.2j)) == keyb(np.clongdouble(1.1+2.2j))

h_int64 = keyb(np.int64(1))

import unittest.mock
with unittest.mock.patch("pytools.persistent_dict.IS_BIGENDIAN", True):
# Very crude big-endian test. Apparently, there is no way to
# create a numpy scalar (not an np.array!) of a specific byte order.
if sys.byteorder == "big":
# no need to swap
be_val = np.int64(1)
else:
be_val = np.int64(1).byteswap()
assert h_int64 == keyb(be_val)


@pytest.mark.parametrize("dict_impl", ("immutabledict", "frozendict",
"constantdict",
Expand Down

0 comments on commit dbe4e5f

Please sign in to comment.