Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions steer_core/Mixins/Dunder.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,17 @@ def __eq__(self, other):
return True

def __hash__(self):
"""Hash based on object identity.
"""Return a stable hash compatible with value-based equality.

Because the objects using this mixin are mutable, a content-based
hash would be unstable. Using ``id()`` means that two distinct
objects that compare equal via ``__eq__`` will have different
hashes -- avoid using these objects as ``set`` members or ``dict``
keys when value-based identity matters.
Instances using this mixin are mutable, so hashing their property
values would make their hash unstable. A constant hash preserves
the requirement that objects which compare equal have equal hashes
while allowing ``dict`` and ``set`` lookups to use ``__eq__``.

The tradeoff is that hash-based lookups among these objects are
linear rather than constant-time.
"""
return hash(id(self))
return 0

def __str__(self):
"""
Expand All @@ -276,4 +278,3 @@ def __repr__(self):
Official string representation of the instance.
"""
return self.__str__()

15 changes: 10 additions & 5 deletions test/test_dunder_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,17 @@ def test_different_name(self, sample_obj):

class TestDunderHash:

def test_hash_is_identity_based(self, sample_obj):
assert hash(sample_obj) == hash(id(sample_obj))
def test_equal_objects_have_equal_hashes(self, sample_obj):
equivalent = SampleObject(name="test", value=1.0)

def test_different_objects_different_hash(self, sample_obj):
other = SampleObject()
assert hash(sample_obj) != hash(other)
assert sample_obj == equivalent
assert hash(sample_obj) == hash(equivalent)

def test_equivalent_object_resolves_dict_key(self, sample_obj):
equivalent = SampleObject(name="test", value=1.0)
values = {sample_obj: 7}

assert values[equivalent] == 7


class TestDunderStr:
Expand Down
Loading