Skip to content

Do not crash when folding constants that overflow - #21820

Open
Eljees wants to merge 1 commit into
python:masterfrom
Eljees:fix/17008-17534-constant-fold-overflow
Open

Do not crash when folding constants that overflow#21820
Eljees wants to merge 1 commit into
python:masterfrom
Eljees:fix/17008-17534-constant-fold-overflow

Conversation

@Eljees

@Eljees Eljees commented Aug 7, 2026

Copy link
Copy Markdown

Fixes #17008.
Fixes #17534.

These turned out to be two ends of the same pipe, so they are fixed together.

Folding overflows (#17008). constant_fold_binary_int_op and constant_fold_binary_float_op take unbounded ints, and several operations cannot produce a result for large operands. Calling them directly on current master:

int /                        OverflowError: integer division result too large for a float
int << (count > ssize_t)     OverflowError: too many digits in integer
float +  - * / // %          OverflowError: int too large to convert to float
float ** (control)           OK -> None

The ** branches already return None in exactly this situation, so the repository was answering its own question — folding is an optimization, and when it cannot produce a value the expression should simply stand. The other seven paths now do the same.

value_repr (#17534). repr() of an int is bounded by sys.set_int_max_str_digits(), so a LiteralType built from a folded power raised ValueError: Exceeds the limit (4300 digits). It now falls back to hex(), which is lossless and unbounded. This is @devdanzin's suggestion from the thread.

The two are connected: int ** builds the huge value that later explodes in value_repr. Guarding folding alone would leave literals that come from other paths, so both sides are handled.

Verified: the four new tests fail on the unpatched tree with exactly the exceptions above, and pass with the change. mypy/test/testtypes.py goes 119 → 120 passed (2 skipped) with no other movement. black and ruff check clean.

Small operands are covered by a test to pin that folding still happens (6 / 3 == 2.0, 1 << 4 == 16, 2.0 ** 3 == 8.0).

AI-assisted (LLM used for drafting); the reproductions and runs above are mine.

@github-actions

This comment has been minimized.

@Eljees
Eljees force-pushed the fix/17008-17534-constant-fold-overflow branch from 87fe25b to d871b03 Compare August 8, 2026 06:39
@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mypy crashes when using reveal_type on large literal int Overflow errors in constant_fold_binary_float_op and constant_fold_binary_int_op

1 participant