Skip to content

Commit

Permalink
KeyBuilder: support ABC, ABCMeta
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasdiener committed Jan 31, 2024
1 parent 1c88a79 commit 79613db
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 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

@staticmethod
def update_for_int(key_hash, key):
sz = 8
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():
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())


if __name__ == "__main__":
if len(sys.argv) > 1:
exec(sys.argv[1])
Expand Down

0 comments on commit 79613db

Please sign in to comment.