diff --git a/cirq-core/cirq/ops/linear_combinations.py b/cirq-core/cirq/ops/linear_combinations.py index 0d08f2e7def..eb4215f675c 100644 --- a/cirq-core/cirq/ops/linear_combinations.py +++ b/cirq-core/cirq/ops/linear_combinations.py @@ -798,7 +798,10 @@ def __isub__(self, other): def __sub__(self, other): if not isinstance(other, (numbers.Complex, PauliString, PauliSum)): - return NotImplemented + if hasattr(other, 'gate') and isinstance(other.gate, identity.IdentityGate): + other = PauliString(other) + else: + return NotImplemented result = self.copy() result -= other return result diff --git a/cirq-core/cirq/ops/pauli_string_test.py b/cirq-core/cirq/ops/pauli_string_test.py index 13231df9409..952c9f333f0 100644 --- a/cirq-core/cirq/ops/pauli_string_test.py +++ b/cirq-core/cirq/ops/pauli_string_test.py @@ -2137,3 +2137,19 @@ def test_resolve(resolve_fn): pst = cirq.PauliString({q: 'x'}, coefficient=t) ps1 = cirq.PauliString({q: 'x'}, coefficient=1j) assert resolve_fn(pst, {'t': 1j}) == ps1 + + +def test_pauli_ops_identity_gate_operation(): + q = cirq.LineQubit(0) + paulis = (cirq.I(q), cirq.X(q), cirq.Y(q), cirq.Z(q)) + for p1 in paulis: + for p2 in paulis: + # TODO: Issue #7280 - Support addition and subtraction of identity gate operations. + if p1 == cirq.I(q) and p2 == cirq.I(q): + continue + assert isinstance( + p1 + p2, (cirq.PauliSum, cirq.PauliString) + ), f"Addition failed for {p1} + {p2}" + assert isinstance( + p1 - p2, (cirq.PauliSum, cirq.PauliString) + ), f"Subtraction failed for {p1} - {p2}"