Skip to content

Commit

Permalink
Ensure that Parameters compare equal when they have the same hash (#1…
Browse files Browse the repository at this point in the history
…1652)

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).
  • Loading branch information
wshanks committed Feb 23, 2024
1 parent ec38b6e commit 3e6b646
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion qiskit/circuit/parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions releasenotes/notes/parameter-hash-eq-645f9de55aa78d02.yaml
Original file line number Diff line number Diff line change
@@ -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).
4 changes: 4 additions & 0 deletions test/python/circuit/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down

0 comments on commit 3e6b646

Please sign in to comment.