python/cpython · error · OverflowError

Cannot convert infinity to integer

Error message

Cannot convert infinity to integer

What it means

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.

Source

Thrown at Lib/_pydecimal.py:1582

        return other.__floordiv__(self, context=context)

    def __float__(self):
        """Float representation."""
        if self._isnan():
            if self.is_snan():
                raise ValueError("Cannot convert signaling NaN to float")
            s = "-nan" if self._sign else "nan"
        else:
            s = str(self)
        return float(s)

    def __int__(self):
        """Converts self to an int, truncating if necessary."""
        if self._is_special:
            if self._isnan():
                raise ValueError("Cannot convert NaN to integer")
            elif self._isinfinity():
                raise OverflowError("Cannot convert infinity to integer")
        s = (-1)**self._sign
        if self._exp >= 0:
            return s*int(self._int)*10**self._exp
        else:
            return s*int(self._int[:self._exp] or '0')

    __trunc__ = __int__

    @property
    def real(self):
        return self

    @property
    def imag(self):
        return Decimal(0)

    def conjugate(self):
        return self

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Check is_infinite() before conversion and cap or reject explicitly
  2. If Infinity arose from overflow, increase Context.prec or enable the Overflow trap to fail at the computation site
  3. Map infinity to a domain-specific maximum instead of int() conversion

Example fix

// before
n = int(total)  # OverflowError when total is Decimal('Infinity')

// after
if total.is_infinite():
    raise OverflowError('aggregate overflowed')
n = int(total)
Defensive patterns

Strategy: validation

Validate before calling

def safe_int(d):
    if d.is_infinite():
        raise OverflowError(f'cannot convert {d} to int')
    return int(d)

Type guard

def is_int_convertible(d) -> bool:
    return not d._is_special

Try / catch

try:
    n = int(d)
except OverflowError:
    n = max_int_cap  # if clamping is acceptable policy
except ValueError:
    n = 0  # NaN policy

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/059bd8c68c15056c. Report an issue: GitHub.