Skip to content

Fix crash on union replacement when expanding a variadic tuple unpack - #22109

Open
Madin-H23 wants to merge 2 commits into
python:masterfrom
Madin-H23:fix/expand-type-union-replacement-crash
Open

Madin-H23 wants to merge 2 commits into
python:masterfrom
Madin-H23:fix/expand-type-union-replacement-crash

Conversation

@Madin-H23

Copy link
Copy Markdown

Fixes #22108

expand_unpack raised RuntimeError: Invalid type replacement to expand: tuple[*tuple[Any, ...]] | Any when a type variable tuple was expanded with a union replacement. Unions reach this point when a conditional expression is used as a type argument: infer_function_type_arguments_using_context infers the union as the type argument, and apply_generic_arguments then expands it (see the traceback in the issue).

Change

Add UnionType to the carry-over fallback in expand_unpack, same as the existing AnyType/UninhabitedType branch directly above it (whose comment already describes this exact pattern: "These types may appear here as a result of user error or failed inference"). The union is carried over into *tuple[<union>] instead of crashing, preserving the type information.

Tests

test_expand_unpack_union_replacement in mypy/test/testtypes.py constructs tuple[*Ts] with the isomorphic union replacement from the issue and asserts the expansion completes with the union carried over. It fails with the RuntimeError on unpatched code and passes with the fix. The existing expand tests (test_expand_*) and the variadic checker tests (typevar_tuple/variadic selections, 168 cases) pass unchanged.

Expanding *Ts with a union replacement (e.g. tuple[*tuple[Any, ...]] | Any
inferred from a conditional expression used as a type argument) raised
RuntimeError from expand_unpack, since unions were not handled there.
Carry the union over into the expansion instead, same as the existing
Any/Never fallback above. (GH#22108)
@github-actions

This comment has been minimized.

@github-actions

github-actions Bot commented Oct 5, 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.

Crash with RuntimeError: Invalid type replacement to expand: tuple[*tuple[Any, ...]] | Any

1 participant