From 760679a8af634a7531a81d3671dd80517c6b540b Mon Sep 17 00:00:00 2001 From: Christian Hill Date: Wed, 27 Jul 2022 15:59:27 +0200 Subject: [PATCH] =?UTF-8?q?Silently=20change=20hv=20to=20h=CE=BD=20in=20?= =?UTF-8?q?=5Fparse=5Fformula=20and=20add=20a=20hash=20method?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- setup.py | 2 +- src/pyvalem/formula.py | 18 ++++++++++++------ tests/test_formula.py | 10 ++++++++++ 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/setup.py b/setup.py index a3cf6c8..e396ee5 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setup( name="pyvalem", - version="2.5.9", + version="2.5.10", description="A package for managing simple chemical species and states", long_description=long_description, long_description_content_type="text/x-rst", diff --git a/src/pyvalem/formula.py b/src/pyvalem/formula.py index 25eaed6..29cb50a 100644 --- a/src/pyvalem/formula.py +++ b/src/pyvalem/formula.py @@ -200,9 +200,10 @@ class Formula: Notes ----- - The ``__repr__`` method is overloaded to provide a *canonicalised* representation - of the formula. The idea is that two formulas representing the same physical entity - will have the same ``repr(formula)`` representation. + The ``__repr__`` method is intended to be a *canonicalised* representation + of the formula, but no check is made to ensure that a single formula is used + to describe a unique species (e.g. "HD" and "DH" and "H(2H)" all have + different __repr__ representations. Examples -------- @@ -321,6 +322,10 @@ def _parse_formula(self, formula): if formula == "e": # Quietly convert e to e-. self.formula = formula = "e-" + + if self.formula == "hv": + self.formula = "hν" + if formula in special_cases: for attr, val in special_cases[formula].items(): setattr(self, attr, val) @@ -506,12 +511,13 @@ def _get_charge_reps(charge): return "", "", "" def __repr__(self): - if self.formula == "hv": - return "hν" return self.formula + def __hash__(self): + return hash(self.formula) + def __eq__(self, other): - return repr(self.formula) == repr(other.formula) + return self.formula == other.formula def _stoichiometric_formula_atomic_number(self): """Return a list of atoms/isotopes and their stoichiometries. diff --git a/tests/test_formula.py b/tests/test_formula.py index cb3950b..9fd1779 100644 --- a/tests/test_formula.py +++ b/tests/test_formula.py @@ -163,6 +163,16 @@ def test_parse_fail(self): self.assertRaises(FormulaParseError, Formula, "H3O^+") self.assertRaises(FormulaParseError, Formula, "H_2S") + def test_formula_hash(self): + f1 = Formula("hv") + f2 = Formula("Ar") + test_dict = {f1: 0, f2: "a"} + test_set = set((f1, f1, f2)) + + f3 = Formula("hν") + self.assertEqual(hash(f1), hash(f3)) + self.assertEqual(repr(f1), repr(f3)) + if __name__ == "__main__": unittest.main()