{"record":{"id":"a3f15e461a1d991a","repo":"pytest-dev/pytest","slug":"absolute-tolerance-for-a-scalar-value-must-be-an-i","errorCode":null,"errorMessage":"absolute tolerance for a scalar value must be an int, float or Decimal, got {type(abs).__name__}","messagePattern":"absolute tolerance for a scalar value must be an int, float or Decimal, got (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/_pytest/approx.py","lineNumber":460,"sourceCode":"        expected: ExpectedT,\n        rel: float | Decimal | timedelta | None,\n        abs: float | Decimal | timedelta | None,\n        nan_ok: bool,\n    ) -> None:\n        __tracebackhide__ = True\n        if rel is not None:\n            if not isinstance(rel, (int, float, Decimal)):\n                raise TypeError(\n                    f\"relative tolerance for a scalar value must be an int, float or Decimal, \"\n                    f\"got {type(rel).__name__}\"\n                )\n            if not isinstance(expected, SupportsAbs):\n                raise TypeError(\n                    f\"expected value must support abs(...) when relative tolerance is used, \"\n                    f\"got {type(expected).__name__}\"\n                )\n        if abs is not None and not isinstance(abs, (int, float, Decimal)):\n            raise TypeError(\n                f\"absolute tolerance for a scalar value must be an int, float or Decimal, \"\n                f\"got {type(abs).__name__}\"\n            )\n        super().__init__(expected, rel=rel, abs=abs, nan_ok=nan_ok)\n\n    def __repr__(self) -> str:\n        \"\"\"Return a string communicating both the expected value and the\n        tolerance for the comparison being made.\n\n        For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``.\n        \"\"\"\n        # Don't show a tolerance for values that aren't compared using\n        # tolerances, i.e. non-numerics and infinities. Need to call abs to\n        # handle complex numbers, e.g. (inf + 1j).\n        if (\n            _is_bool(self.expected)\n            or (not isinstance(self.expected, Complex | Decimal))\n            or math.isinf(abs(self.expected))","sourceCodeStart":442,"sourceCodeEnd":478,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/approx.py#L442-L478","documentation":"ApproxScalar.__init__ validates that an absolute tolerance (abs) must be an int, float, or Decimal. Other types (string, timedelta, list) are rejected with the offending type name. This mirrors the rel validation and fails fast because abs is later compared numerically in the tolerance property.","triggerScenarios":"Passing abs='0.001', abs=timedelta(seconds=1) to a scalar (non-datetime) approx, abs=[0.1], abs=None-as-string. Triggered at ApproxScalar.__init__ (src/_pytest/approx.py:459-463). Note: timedelta is valid only for datetime/timedelta expected values (handled by ApproxTimedelta), not for scalars.","commonSituations":"Copying abs=timedelta(...) syntax from datetime examples into numeric comparisons; loading tolerance from config as a string; passing a numpy float (accepted since it subclasses Python float via __class__).","solutions":["Pass abs as a plain float: `approx(1.0, abs=1e-3)`.","Cast config-supplied values: `abs=float(cfg['abs'])`.","For Decimal expected, pass Decimal abs: `approx(Decimal('1'), abs=Decimal('0.001'))`."],"exampleFix":"# before\napprox(1.0, abs=timedelta(seconds=1))\n# after\napprox(1.0, abs=1e-3)","handlingStrategy":"validation","validationCode":"from decimal import Decimal\ndef is_valid_abs(abs_tol) -> bool:\n    return abs_tol is None or isinstance(abs_tol, (int, float, Decimal))\n# usage\nabs_tol = float(config['abs']) if isinstance(config['abs'], str) else config['abs']\nassert is_valid_abs(abs_tol)\nassert actual == approx(expected, abs=abs_tol)","typeGuard":"from decimal import Decimal\ndef is_scalar_abs(v) -> bool:\n    return v is None or isinstance(v, (int, float, Decimal))","tryCatchPattern":null,"preventionTips":["Pass abs as a literal float or Decimal for scalar comparisons.","Reserve timedelta abs for datetime/timedelta expected values.","Cast string tolerances with float(...) at config load time."],"tags":["pytest","approx","tolerance","type-validation","scalar"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}