{"record":{"id":"05b56d3b2fda749a","repo":"pytest-dev/pytest","slug":"approx-is-not-supported-in-a-boolean-context-di","errorCode":null,"errorMessage":"approx() is not supported in a boolean context.\nDid you mean: `assert a == approx(b)`?","messagePattern":"approx\\(\\) is not supported in a boolean context\\.\nDid you mean: `assert a == approx\\(b\\)`\\?","errorType":"exception","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"src/_pytest/approx.py","lineNumber":112,"sourceCode":"    @abc.abstractmethod\n    def __repr__(self) -> str:\n        raise NotImplementedError\n\n    def _repr_compare(self, other_side) -> list[str]:\n        return [\n            \"comparison failed\",\n            f\"Obtained: {other_side}\",\n            f\"Expected: {self}\",\n        ]\n\n    def __eq__(self, actual) -> bool:\n        return all(\n            a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)\n        )\n\n    def __bool__(self):\n        __tracebackhide__ = True\n        raise AssertionError(\n            \"approx() is not supported in a boolean context.\\nDid you mean: `assert a == approx(b)`?\"\n        )\n\n    # Ignore type because of https://github.com/python/mypy/issues/4266.\n    __hash__ = None  # type: ignore\n\n    def _approx_scalar(self, x) -> ApproxScalar[Any] | ApproxTimedelta:\n        if isinstance(x, Decimal):\n            return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)\n        if isinstance(x, (datetime, timedelta)):\n            return ApproxTimedelta(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)\n        return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)\n\n    def _yield_comparisons(self, actual: object):\n        \"\"\"Yield all the pairs of numbers to be compared.\n\n        This is used to implement the `__eq__` method.\n        \"\"\"","sourceCodeStart":94,"sourceCodeEnd":130,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/approx.py#L94-L130","documentation":"pytest.approx() returns an Approx object whose only meaningful operation is equality comparison (e.g. `a == approx(b)`). The class deliberately defines __bool__ to raise AssertionError so that misuses like `assert approx(x)` or `if approx(x):` fail loudly instead of silently passing or failing. pytest throws this because a bare truthiness check on an Approx value has no sensible meaning and would otherwise evaluate to True/False unpredictably.","triggerScenarios":"Calling bool(approx(x)), using approx(x) in an if/while/and/or expression, writing `assert approx(x)` without a comparison operand, passing approx(x) to a function that evaluates its argument's truthiness, or storing the result and later using it in a conditional. Triggered at Approx.__bool__ (src/_pytest/approx.py:110-114).","commonSituations":"Copy-pasting a test skeleton and forgetting the left-hand operand (assert approx(expected) instead of assert actual == approx(expected)); refactoring a comparison into a helper that returns the approx object; using approx() with pytest.warns/raises which evaluate truthiness of the returned context.","solutions":["Always write approx() on the right-hand side of ==: `assert actual == approx(expected)`.","If you stored approx in a variable, compare it explicitly: `assert actual == expected_approx`.","Search the failing test file for `assert approx(` (regex) and add the missing `actual ==` operand."],"exampleFix":"# before\nassert approx(0.3)\n# after\nassert 0.1 + 0.2 == approx(0.3)","handlingStrategy":"validation","validationCode":"# Before using an approx value, ensure it is always compared, never evaluated as bool.\n# Static check (regex in pre-commit / lint): reject `assert approx(` without `==`.\nimport re\ndef assert_uses_comparison(line: str) -> bool:\n    # flag bare `assert approx(...)` or `assert <name> ` where name holds an Approx\n    return bool(re.search(r'\\bassert\\s+approx\\(', line)) and '==' not in line","typeGuard":"from pytest import Approx\ndef is_approx(obj) -> bool:\n    return isinstance(obj, Approx)","tryCatchPattern":null,"preventionTips":["Always write approx() on the right of ==: assert actual == approx(expected).","Lint for the regex `assert\\s+approx\\(` to catch bare boolean-context usage.","Never pass an Approx object to a function that evaluates truthiness."],"tags":["pytest","approx","assertion","boolean-context","misuse"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}