{"record":{"id":"059bd8c68c15056c","repo":"python/cpython","slug":"cannot-convert-infinity-to-integer","errorCode":null,"errorMessage":"Cannot convert infinity to integer","messagePattern":"Cannot convert infinity to integer","errorType":"exception","errorClass":"OverflowError","httpStatus":null,"severity":"error","filePath":"Lib/_pydecimal.py","lineNumber":1582,"sourceCode":"        return other.__floordiv__(self, context=context)\n\n    def __float__(self):\n        \"\"\"Float representation.\"\"\"\n        if self._isnan():\n            if self.is_snan():\n                raise ValueError(\"Cannot convert signaling NaN to float\")\n            s = \"-nan\" if self._sign else \"nan\"\n        else:\n            s = str(self)\n        return float(s)\n\n    def __int__(self):\n        \"\"\"Converts self to an int, truncating if necessary.\"\"\"\n        if self._is_special:\n            if self._isnan():\n                raise ValueError(\"Cannot convert NaN to integer\")\n            elif self._isinfinity():\n                raise OverflowError(\"Cannot convert infinity to integer\")\n        s = (-1)**self._sign\n        if self._exp >= 0:\n            return s*int(self._int)*10**self._exp\n        else:\n            return s*int(self._int[:self._exp] or '0')\n\n    __trunc__ = __int__\n\n    @property\n    def real(self):\n        return self\n\n    @property\n    def imag(self):\n        return Decimal(0)\n\n    def conjugate(self):\n        return self","sourceCodeStart":1564,"sourceCodeEnd":1600,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pydecimal.py#L1564-L1600","documentation":"int(Decimal('Infinity')) raises OverflowError('Cannot convert infinity to integer') — unlike float('inf'), Python ints are unbounded but infinity is not an integer, so there is no target value. __trunc__ shares this behavior.","triggerScenarios":"int(Decimal('Infinity')); int(Decimal('-Inf')); math.trunc(Decimal('inf')); sum() of decimals that overflowed to infinity (with Overflow trap disabled) then converted to int.","commonSituations":"Aggregations where division/overflow produced Infinity under a context with Overflow untrapped; parsed 'inf' strings from logs/scientific notation feeds fed into int() for counting.","solutions":["Check is_infinite() before conversion and cap or reject explicitly","If Infinity arose from overflow, increase Context.prec or enable the Overflow trap to fail at the computation site","Map infinity to a domain-specific maximum instead of int() conversion"],"exampleFix":"// before\nn = int(total)  # OverflowError when total is Decimal('Infinity')\n\n// after\nif total.is_infinite():\n    raise OverflowError('aggregate overflowed')\nn = int(total)","handlingStrategy":"validation","validationCode":"def safe_int(d):\n    if d.is_infinite():\n        raise OverflowError(f'cannot convert {d} to int')\n    return int(d)","typeGuard":"def is_int_convertible(d) -> bool:\n    return not d._is_special","tryCatchPattern":"try:\n    n = int(d)\nexcept OverflowError:\n    n = max_int_cap  # if clamping is acceptable policy\nexcept ValueError:\n    n = 0  # NaN policy","preventionTips":["Trap Overflow in the context so infinity is caught where it is produced","Guard with is_infinite() before int()/math.trunc() on computed aggregates","Remember json.loads('Infinity') succeeds — validate parsed values"],"tags":["decimal","int-conversion","infinity","overflow","overflowerror"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}