OverflowError, what it means and how to fix it

Python integers grow without limit, but floats and the C machinery underneath them do not. OverflowError is raised when a result or a conversion crosses that boundary: turning an enormous int into a float, math.exp(1000), or passing an out-of-range value to a function backed by C types. The message is one of a few wordings (“math range error”, “int too large to convert to float”, a bare errno result out of range), all meaning the number no longer fits.

What it looks like

import math
print(math.exp(1000))

Traceback (most recent call last):
  File "main.py", line 2, in <module>
OverflowError: math range error

print(float(10 ** 400))
# OverflowError: int too large to convert to float

The fix, in order

  1. Identify which boundary was crossed. Converting to float fails above roughly 1.8e308; math.exp overflows near an input of 710; time and C-backed functions have their own ranges. The failing function in the traceback names the boundary.
  2. Work in logarithms when magnitudes explode. If you only need to compare or rank huge quantities, compare their logs. Exponentials in probability code are the classic case: compute in log space and exponentiate only final, bounded differences.
  3. Use Decimal when precision at scale is the point. Financial and scientific code that genuinely needs very large or very precise numbers belongs in the decimal module, whose range and precision are configurable, at a speed cost.
  4. Cap and validate inputs. A factorial, an exponent, or a growth loop fed by user or file data should have its input range checked; overflow from absurd input is a validation bug wearing a math costume.
  5. For timestamps and IDs, convert through strings or keep values as ints end to end; routing a huge int through a float silently loses precision even before it overflows.

If it still happens

Repeated overflow in code that “worked last month” often tracks data growth: the inputs crept past the boundary the code always had. Check whether the overflowing value correlates with the largest records; if so, the log-space or Decimal change is structural, not a patch.

Common questions

If Python ints are unlimited, why can a number be too large? Ints are unlimited inside Python's own arithmetic. The overflow happens at the borders: converting an int to a float (which has a fixed range), or handing it to a C function or a fixed-width type. The border is where the error lives.

What is the difference between OverflowError and MemoryError? Overflow is about a single number exceeding a numeric range. MemoryError is about total allocation across the process. A tiny program can overflow with one huge computation while using almost no memory.

Related errors

ZeroDivisionError · MemoryError · RecursionError