Skip to content

Commit

Permalink
Merge pull request #226 from DNIIBOY/hashed-substance
Browse files Browse the repository at this point in the history
Add __hash__ method to Substance class
  • Loading branch information
bjodah committed Mar 5, 2024
2 parents 1ef1bf6 + 5c5f09f commit 7839245
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
10 changes: 10 additions & 0 deletions chempy/chemistry.py
Expand Up @@ -98,6 +98,16 @@ def __eq__(self, other):
return False
return True

def __hash__(self) -> int:
hashed_values = []
for key in self.attrs:
value = getattr(self, key)
if isinstance(value, dict):
hashed_values.append(hash(tuple(sorted(value.items()))))
else:
hashed_values.append(hash(value))
return sum(hashed_values)

@property
def charge(self):
"""Convenience property for accessing ``composition[0]``"""
Expand Down
2 changes: 2 additions & 0 deletions chempy/tests/test_chemistry.py
Expand Up @@ -40,6 +40,8 @@ def test_Substance():
assert s.composition == {0: 1, 1: 1}
assert s.charge == 1
assert abs(s.mass - 1.008) < 1e-3
assert s in {s: 1}
assert hash(s) != hash(Substance.from_formula("He"))


def test_Substance__2():
Expand Down

0 comments on commit 7839245

Please sign in to comment.