Skip to content

Commit

Permalink
KeyBuilder: support ABC, ABCMeta (#194)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener authored Feb 2, 2024
1 parent 5277fdd commit 19db631
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pytools/persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,8 @@ def update_for_type(key_hash, key):
key_hash.update(
f"{key.__module__}.{key.__qualname__}.{key.__name__}".encode("utf-8"))

update_for_ABCMeta = update_for_type # noqa: N815

@staticmethod
def update_for_int(key_hash, key):
sz = 8
Expand Down Expand Up @@ -352,7 +354,7 @@ def update_for_frozenset(self, key_hash, key):
update_for_FrozenOrderedSet = update_for_frozenset # noqa: N815

@staticmethod
def update_for_NoneType(key_hash, key): # noqa
def update_for_NoneType(key_hash, key): # noqa: N802
del key
key_hash.update(b"<None>")

Expand Down
30 changes: 30 additions & 0 deletions pytools/test/test_persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,36 @@ def test_frozenorderedset_hashing():
assert keyb(FrozenOrderedSet([1, 2, 3])) == keyb(FrozenOrderedSet([3, 2, 1]))


def test_ABC_hashing(): # noqa: N802
from abc import ABC, ABCMeta

keyb = KeyBuilder()

class MyABC(ABC):
pass

assert keyb(MyABC) != keyb(ABC)

with pytest.raises(TypeError):
keyb(MyABC())

with pytest.raises(TypeError):
keyb(ABC())

class MyABC2(MyABC):
def update_persistent_hash(self, key_hash, key_builder):
key_builder.rec(key_hash, 42)

assert keyb(MyABC2) != keyb(MyABC)
assert keyb(MyABC2())

class MyABC3(metaclass=ABCMeta): # noqa: B024
def update_persistent_hash(self, key_hash, key_builder):
key_builder.rec(key_hash, 42)

assert keyb(MyABC3) != keyb(MyABC) != keyb(MyABC3())


def test_class_hashing():
keyb = KeyBuilder()

Expand Down

0 comments on commit 19db631

Please sign in to comment.