Skip to content

Commit d62a508

Browse files
authored
Fix crash on Unpack used without arguments in class bases (#21470)
Fixes #21467. `analyze_unbound_tvar` accessed `t.args[0]` unconditionally when a class base was `Unpack` with no arguments (e.g. `class C(Protocol[Unpack]): ...`), raising `IndexError: tuple index out of range` during semantic analysis. This adds a guard returning `None` in that case, so the existing "Free type variable expected in Protocol[...]" error is reported instead of crashing. Added a regression test in `check-typevar-tuple.test`.
1 parent e53693b commit d62a508

2 files changed

Lines changed: 11 additions & 0 deletions

File tree

mypy/semanal.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2403,6 +2403,9 @@ def analyze_unbound_tvar(self, t: Type) -> tuple[str, TypeVarLikeExpr] | None:
24032403
if isinstance(t, UnboundType):
24042404
sym = self.lookup_qualified(t.name, t)
24052405
if sym and sym.fullname in UNPACK_TYPE_NAMES:
2406+
if not t.args:
2407+
# Unpack used without arguments, e.g. `Protocol[Unpack]`
2408+
return None
24062409
inner_t = t.args[0]
24072410
if isinstance(inner_t, UnboundType):
24082411
return self.analyze_unbound_tvar_impl(inner_t, is_unpacked=True)

test-data/unit/check-typevar-tuple.test

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2765,3 +2765,11 @@ def func(d: Callable[[Unpack[Ts]], T]) -> T: ...
27652765
y = func[1, int] # E: Type application is only supported for generic classes \
27662766
# E: Invalid type: try using Literal[1] instead?
27672767
[builtins fixtures/tuple.pyi]
2768+
2769+
[case testTypeVarTupleUnpackWithoutArgsInProtocol]
2770+
# https://github.com/python/mypy/issues/21467
2771+
from typing import Protocol, Unpack
2772+
2773+
class C(Protocol[Unpack]): # E: Free type variable expected in Protocol[...]
2774+
pass
2775+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)