pytest-dev/pytest · error · AssertionError

approx() is not supported in a boolean context. Did you mean

Error message

approx() is not supported in a boolean context.
Did you mean: `assert a == approx(b)`?

What it means

An approx() object is not a boolean; it is a comparison helper meant to be used only as `assert a == approx(b)`. If used in a boolean context (if, bool(), conditional, or bare `assert approx(b)`), pytest raises AssertionError in __bool__ because the result is meaningless without an actual value to compare against.

Source

Thrown at src/_pytest/approx.py:112

    @abc.abstractmethod
    def __repr__(self) -> str:
        raise NotImplementedError

    def _repr_compare(self, other_side) -> list[str]:
        return [
            "comparison failed",
            f"Obtained: {other_side}",
            f"Expected: {self}",
        ]

    def __eq__(self, actual) -> bool:
        return all(
            a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)
        )

    def __bool__(self):
        __tracebackhide__ = True
        raise AssertionError(
            "approx() is not supported in a boolean context.\nDid you mean: `assert a == approx(b)`?"
        )

    # Ignore type because of https://github.com/python/mypy/issues/4266.
    __hash__ = None  # type: ignore

    def _approx_scalar(self, x) -> ApproxScalar[Any] | ApproxTimedelta:
        if isinstance(x, Decimal):
            return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
        if isinstance(x, (datetime, timedelta)):
            return ApproxTimedelta(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
        return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)

    def _yield_comparisons(self, actual: object):
        """Yield all the pairs of numbers to be compared.

        This is used to implement the `__eq__` method.
        """

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Use approx() only in an equality comparison: assert actual == approx(expected).
  2. Replace `if approx(x):` with a concrete comparison: if abs(actual - expected) < tol.
  3. Review the hint in the error message: 'Did you mean: assert a == approx(b)?'

Example fix

# before
assert approx(3.0)  # missing the actual value

# after
assert result == approx(3.0)
Defensive patterns

Strategy: validation

Prevention

When it happens

Trigger: Writing `if approx(x):`, `bool(approx(x))`, or `assert approx(x)` without a comparison. The __bool__ dunder is invoked, raising AssertionError with a hint.

Common situations: Developers unfamiliar with approx() who treat it like a predicate, or who write `assert approx(x)` instead of `assert a == approx(x)`.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/05b56d3b2fda749a.json. Report an issue: GitHub.