From 46f2de020fe73662fd2d7d8d9e922b80651a24b9 Mon Sep 17 00:00:00 2001 From: Will Shanks Date: Fri, 23 Feb 2024 09:28:37 -0800 Subject: [PATCH] Ensure that Parameters compare equal when they have the same hash (#11652) Previously, only the `Parameter.uuid` was compared, so `Paramemter` instances with different names could compare equal if they had been constructed using a common value for the `uuid` parameter (which is usually not passed explicitly). (cherry picked from commit 3e6b646a3329c234cfb1aef579edff9d944b0c20) --- qiskit/circuit/parameter.py | 2 +- .../notes/parameter-hash-eq-645f9de55aa78d02.yaml | 8 ++++++++ test/python/circuit/test_parameters.py | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 releasenotes/notes/parameter-hash-eq-645f9de55aa78d02.yaml diff --git a/qiskit/circuit/parameter.py b/qiskit/circuit/parameter.py index 8d6eb2e5762d..69a00fd166de 100644 --- a/qiskit/circuit/parameter.py +++ b/qiskit/circuit/parameter.py @@ -138,7 +138,7 @@ def __repr__(self): def __eq__(self, other): if isinstance(other, Parameter): - return self._uuid == other._uuid + return (self._uuid, self._name) == (other._uuid, other._name) elif isinstance(other, ParameterExpression): return super().__eq__(other) else: diff --git a/releasenotes/notes/parameter-hash-eq-645f9de55aa78d02.yaml b/releasenotes/notes/parameter-hash-eq-645f9de55aa78d02.yaml new file mode 100644 index 000000000000..f134de5f00fa --- /dev/null +++ b/releasenotes/notes/parameter-hash-eq-645f9de55aa78d02.yaml @@ -0,0 +1,8 @@ +--- +fixes: + - | + :class:`.Parameter` was updated so that instances that compare equal always + have the same hash. Previously, only the :attr:`.Parameter.uuid` was + compared, so :class:`.Paramemter` instances with different names could + compare equal if they had been constructed using a common value for the + ``uuid`` parameter (which is usually not passed explicitly). diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index 6494fcc463a5..9511ac08654c 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -111,10 +111,14 @@ def test_equality(self): param = Parameter("a") param_copy = Parameter(param.name, uuid=param.uuid) param_different = Parameter("a") + param_same_uuid_diff_name = Parameter("b", uuid=param.uuid) self.assertEqual(param, param, "Parameter does not equal itself") self.assertEqual(param, param_copy, "Parameters with same data are not equal") self.assertNotEqual(param, param_different, "Different Parameters are treated as equal") + self.assertNotEqual( + param, param_same_uuid_diff_name, "Parameters with different names are treated as equal" + ) def test_gate(self): """Test instantiating gate with variable parameters"""