Skip to content

Commit 5f2afae

Browse files
committed
Fix IndexError when unpacking empty tuple in type alias
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 #20913
1 parent 1d8ddd5 commit 5f2afae

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

mypy/expandtype.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ def visit_instance(self, t: Instance) -> Type:
223223
# See: https://github.com/python/mypy/issues/16649
224224
return t.copy_modified(args=args)
225225

226-
if t.type.fullname == "builtins.tuple":
226+
if t.type.fullname == "builtins.tuple" and len(args) > 0:
227227
# Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...]
228228
arg = args[0]
229229
if isinstance(arg, UnpackType):

test-data/unit/check-python312.test

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,3 +2237,17 @@ class D[*Ts](Generic[Unpack[Us]]): # E: Generic[...] base class is redundant \
22372237
# E: Can only use one type var tuple in a class def
22382238
pass
22392239
[builtins fixtures/tuple.pyi]
2240+
2241+
[case testUnpackEmptyTupleInTypeAliasNoCrash]
2242+
# https://github.com/python/mypy/issues/20913
2243+
from typing import Unpack
2244+
2245+
class C[*Ts]:
2246+
pass
2247+
2248+
type T[T, *Ts] = C[*Ts]
2249+
2250+
x: T[bool, Unpack[tuple[()]]]
2251+
reveal_type(x) # N: Revealed type is "__main__.C[()]"
2252+
[builtins fixtures/tuple.pyi]
2253+
[typing fixtures/typing-full.pyi]

0 commit comments

Comments
 (0)