Skip to content

Fix IndexError when unpacking empty tuple in type alias#20931

Open
bxff wants to merge 1 commit intopython:masterfrom
bxff:fix/unpack-index-error
Open

Fix IndexError when unpacking empty tuple in type alias#20931
bxff wants to merge 1 commit intopython:masterfrom
bxff:fix/unpack-index-error

Conversation

@bxff
Copy link

@bxff bxff commented Feb 28, 2026

Crash

mypy crashes with IndexError: list index out of range when using Unpack[tuple[()]] in a PEP 695 type alias:

from typing import Unpack

class C[*Ts]:
    pass

type T[T, *Ts] = C[*Ts]

x: T[bool, Unpack[tuple[()]]]  # crash

Root Cause

In ExpandTypeVisitor.visit_instance(), when handling builtins.tuple instances, the normalization code at line 228 accesses args[0] without checking if args is non-empty. Unpack[tuple[()]] expands to zero items (empty tuple), leaving args as an empty list after expand_type_tuple_with_unpack().

Fix

Added a len(args) > 0 guard to the builtins.tuple normalization condition.

Test Plan

Added testUnpackEmptyTupleInTypeAliasNoCrash in check-python312.test reproducing the exact crash from the issue. Also verified all 191 existing Unpack/TypeVarTuple tests pass.

Fixes #20913

When expanding type arguments for a builtins.tuple instance, the
normalization code accessed args[0] without checking if args was
non-empty. This caused an IndexError when Unpack[tuple[()]] was used
in a type alias, since the empty tuple expansion produces zero args.

Fixes python#20913
@github-actions
Copy link
Contributor

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


type T[T, *Ts] = C[*Ts]

x: T[bool, Unpack[tuple[()]]]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a reveal type to make sure the type is being preserved?

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.

IndexError when unpacking type

2 participants