Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MeasurementValue raises an error when used as boolean #6386

Merged
merged 10 commits into from
Oct 15, 2024
2 changes: 2 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,8 @@

<h3>Bug fixes 🐛</h3>

* `MeasurementValue` now raises an error when it is used as a boolean.
albi3ro marked this conversation as resolved.
Show resolved Hide resolved

* `adjoint_metric_tensor` now works with circuits containing state preparation operations.
[(#6358)](https://github.com/PennyLaneAI/pennylane/pull/6358)

Expand Down
8 changes: 7 additions & 1 deletion pennylane/measurements/mid_measure.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
This module contains the qml.measure measurement.
"""
import uuid
from collections.abc import Hashable
from functools import lru_cache
from typing import Generic, Hashable, Optional, TypeVar, Union
from typing import Generic, Optional, TypeVar, Union

import pennylane as qml
from pennylane.wires import Wires
Expand Down Expand Up @@ -456,6 +457,11 @@ def __invert__(self):
value."""
return self._apply(qml.math.logical_not)

def __bool__(self) -> bool:
raise ValueError(
"The truth value of a MeasurementValue is undefined. To condition on a MeasurementValue, please use qml.cond instead."
)

def __eq__(self, other):
return self._transform_bin_op(lambda a, b: a == b, other)

Expand Down
9 changes: 9 additions & 0 deletions tests/measurements/test_mid_measure.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ def test_label(self, postselect, reset, expected):
class TestMeasurementValueManipulation:
"""Test all the dunder methods associated with the MeasurementValue class"""

def test_error_on_boolean_conversion(self):
"""Test that an error is raised if a measurement value if used as a boolean."""

m = MeasurementValue([mp1], lambda v: v)

with pytest.raises(ValueError, match="The truth value of a MeasurementValue"):
if m:
return

def test_apply_function_to_measurement(self):
"""Test the general _apply method that can apply an arbitrary function to a measurement."""

Expand Down
Loading