GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix crash on invalid recursive variadic alias by ilevkivskyi · Pull Request #21572 · python/mypy

Fix crash on invalid recursive variadic alias #21572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
ilevkivskyi merged 3 commits into python:master from ilevkivskyi:fix-pat-rec-tvt
Jun 3, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

Fix crash on invalid recursive variadic alias #21572

Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
504e6cb
Fix crash on invalid recursive variadic alias
ilevkivskyi May 31, 2026
1ca0a7b
Fix typo
ilevkivskyi May 31, 2026
decd092
Use an alternative approach to fix more crash scenarios
ilevkivskyi Jun 2, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

15 changes: 10 additions & 5 deletions 15 mypy/expandtype.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,16 @@ class ExpandTypeVisitor(TrivialSyntheticTypeTranslator):

variables: Mapping[TypeVarId, Type] # TypeVar id -> TypeVar value

def __init__(self, variables: Mapping[TypeVarId, Type]) -> None:
def __init__(
self, variables: Mapping[TypeVarId, Type], skip_normalization: bool = False
) -> None:
super().__init__()
self.variables = variables
# This flag will skip normalizations that are semantically not needed, but
# require calling get_proper_type(). This is needed during very early stages
# to avoid infinite recursion when detecting invalid/divergent recursive
# type aliases.
self.skip_normalization = skip_normalization

def visit_unbound_type(self, t: UnboundType) -> Type:
return t
Expand Down Expand Up @@ -228,11 +235,9 @@ def visit_instance(self, t: Instance) -> Type:
if t.type.fullname == "builtins.tuple":
# Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...]
arg = args[0]
if isinstance(arg, UnpackType):
if not self.skip_normalization and isinstance(arg, UnpackType):
unpacked = get_proper_type(arg.type)
if isinstance(unpacked, Instance):
# TODO: this and similar asserts below may be unsafe because get_proper_type()
# may be called during semantic analysis before all invalid types are removed.
assert unpacked.type.fullname == "builtins.tuple"
args = list(unpacked.args)
return t.copy_modified(args=args)
Expand Down Expand Up @@ -535,7 +540,7 @@ def visit_tuple_type(self, t: TupleType) -> Type:
if len(items) == 1:
# Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...]
item = items[0]
if isinstance(item, UnpackType):
if not self.skip_normalization and isinstance(item, UnpackType):
unpacked = get_proper_type(item.type)
if isinstance(unpacked, Instance):
# expand_type() may be called during semantic analysis, before invalid unpacks are fixed.
Expand Down
8 changes: 4 additions & 4 deletions 8 mypy/semanal.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4263,6 +4263,8 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool:
# An alias gets updated.
updated = False
if isinstance(existing.node, TypeAlias):
# Invalidate recursive status cache in case it was previously set.
existing.node._is_recursive = None
if existing.node.target != res:
# Copy expansion to the existing alias, this matches how we update base classes
# for a TypeInfo _in place_ if there are nested placeholders.
Expand All @@ -4271,8 +4273,6 @@ def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool:
existing.node.alias_tvars = alias_tvars
existing.node.no_args = no_args
updated = True
# Invalidate recursive status cache in case it was previously set.
existing.node._is_recursive = None
else:
# Otherwise just replace existing placeholder with type alias *in place*.
existing._node = alias_node
Expand Down Expand Up @@ -5830,6 +5830,8 @@ def visit_type_alias_stmt(self, s: TypeAliasStmt) -> None:
):
updated = False
if isinstance(existing.node, TypeAlias):
# Invalidate recursive status cache in case it was previously set.
existing.node._is_recursive = None
if (
existing.node.target != res
or existing.node.alias_tvars != alias_node.alias_tvars
Expand All @@ -5840,8 +5842,6 @@ def visit_type_alias_stmt(self, s: TypeAliasStmt) -> None:
existing.node.default_depends = default_depends
existing.node.alias_tvars = alias_tvars
updated = True
# Invalidate recursive status cache in case it was previously set.
existing.node._is_recursive = None
else:
# Otherwise just replace existing placeholder with type alias *in place*.
existing._node = alias_node
Expand Down
2 changes: 2 additions & 0 deletions 2 mypy/server/astmerge.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,8 @@ def visit_var(self, node: Var) -> None:
super().visit_var(node)

def visit_type_alias(self, node: TypeAlias) -> None:
# Updating alias target can invalidate its recursive status.
node._is_recursive = None
self.fixup_type(node.target)
for v in node.alias_tvars:
self.fixup_type(v)
Expand Down
26 changes: 19 additions & 7 deletions 26 mypy/typeanal.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
BoolTypeQuery,
CallableArgument,
CallableType,
CollectAliasesVisitor,
DeletedType,
EllipsisType,
ErasedType,
Expand Down Expand Up @@ -275,7 +276,9 @@ def __init__(
self.prohibit_special_class_field_types = prohibit_special_class_field_types
# Allow variables typed as Type[Any] and type (useful for base classes).
self.allow_type_any = allow_type_any
self.allow_type_var_tuple = False
# Level of nesting at which a TypeVarTuple is allowed. Note we specify exact level
# to prohibit things like Unpack[list[Ts]], which are not supported.
self.allow_type_var_tuple = -1
self.allow_unpack = allow_unpack
# Set when we are analyzing a default of a type variable.
self.analyzing_tvar_def = analyzing_tvar_def
Expand Down Expand Up @@ -453,7 +456,7 @@ def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool)
self.fail(msg, t, code=codes.VALID_TYPE)
return AnyType(TypeOfAny.from_error)
assert isinstance(tvar_def, TypeVarTupleType)
if not self.allow_type_var_tuple:
if self.allow_type_var_tuple != self.nesting_level:
self.fail(
f'TypeVarTuple "{t.name}" is only valid with an unpack',
t,
Expand Down Expand Up @@ -808,9 +811,9 @@ def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Typ
if not self.allow_unpack:
self.fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE)
return AnyType(TypeOfAny.from_error)
self.allow_type_var_tuple = True
self.allow_type_var_tuple = self.nesting_level + 1
result = UnpackType(self.anal_type(t.args[0]), line=t.line, column=t.column)
self.allow_type_var_tuple = False
self.allow_type_var_tuple = -1
return result
elif fullname in SELF_TYPE_NAMES:
if t.args:
Expand Down Expand Up @@ -1161,9 +1164,9 @@ def visit_unpack_type(self, t: UnpackType) -> Type:
if not self.allow_unpack:
self.fail(message_registry.INVALID_UNPACK_POSITION, t.type, code=codes.VALID_TYPE)
return AnyType(TypeOfAny.from_error)
self.allow_type_var_tuple = True
self.allow_type_var_tuple = self.nesting_level + 1
result = UnpackType(self.anal_type(t.type), from_star_syntax=t.from_star_syntax)
self.allow_type_var_tuple = False
self.allow_type_var_tuple = -1
return result

def visit_parameters(self, t: Parameters) -> Type:
Expand Down Expand Up @@ -2500,7 +2503,7 @@ def visit_type_alias_type(self, t: TypeAliasType) -> Type:
return t
new_nodes = self.seen_nodes | {t.alias}
visitor = DivergingAliasDetector(new_nodes)
_ = get_proper_type(t).accept(visitor)
_ = t.expand_once(skip_normalization=True).accept(visitor)
if visitor.diverging:
self.diverging = True
return t
Expand All @@ -2518,6 +2521,15 @@ def detect_diverging_alias(node: TypeAlias, target: Type) -> bool:
They may be handy in rare cases, e.g. to express a union of non-mixed nested lists:
Nested = Union[T, Nested[List[T]]] ~> Union[T, List[T], List[List[T]], ...]
"""
is_recursive = node._is_recursive
if is_recursive is None:
is_recursive = node in node.target.accept(CollectAliasesVisitor())
if not is_recursive:
# Fast path: this is not a recursive alias at all.
return False
# Note we only cache positive case, caching negative case is risky, as this type alias
# (or more importantly any other alias it uses) may be not ready yet.
node._is_recursive = True
visitor = DivergingAliasDetector({node})
_ = target.accept(visitor)
return visitor.diverging
Expand Down
9 changes: 5 additions & 4 deletions 9 mypy/types.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -350,11 +350,11 @@ def __init__(
self.args = args
self.type_ref: str | None = None

def _expand_once(self) -> Type:
def expand_once(self, skip_normalization: bool = False) -> Type:
"""Expand to the target type exactly once.

This doesn't do full expansion, i.e. the result can contain another
(or even this same) type alias. Use this internal helper only when really needed,
(or even this same) type alias. Use this helper only when needed,
its public wrapper mypy.types.get_proper_type() is preferred.
"""
assert self.alias is not None
Expand All @@ -381,7 +381,8 @@ def _expand_once(self) -> Type:
):
mapping[tvar.id] = sub

return self.alias.target.accept(InstantiateAliasVisitor(mapping))
visitor = InstantiateAliasVisitor(mapping, skip_normalization=skip_normalization)
return self.alias.target.accept(visitor)

@property
def is_recursive(self) -> bool:
Expand Down Expand Up @@ -3707,7 +3708,7 @@ def get_proper_type(typ: Type | None) -> ProperType | None:
if isinstance(typ, TypeGuardedType):
typ = typ.type_guard
while isinstance(typ, TypeAliasType):
typ = typ._expand_once()
typ = typ.expand_once()
# TODO: store the name of original type alias on this type, so we can show it in errors.
return cast(ProperType, typ)

Expand Down
4 changes: 3 additions & 1 deletion 4 mypy/types_utils.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@ def is_invalid_recursive_alias(seen_nodes: set[TypeAlias], target: Type) -> bool
if target.alias in seen_nodes:
return True
assert target.alias, f"Unfixed type alias {target.type_ref}"
return is_invalid_recursive_alias(seen_nodes | {target.alias}, get_proper_type(target))
return is_invalid_recursive_alias(
seen_nodes | {target.alias}, target.expand_once(skip_normalization=True)
)
assert isinstance(target, ProperType)
if not isinstance(target, (UnionType, TupleType)):
return False
Expand Down
17 changes: 17 additions & 0 deletions 17 test-data/unit/check-typevar-tuple.test
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,24 @@ z: C
reveal_type(x) # N: Revealed type is "Any"
reveal_type(y) # N: Revealed type is "Any"
reveal_type(z) # N: Revealed type is "tuple[builtins.int, Unpack[builtins.tuple[Any, ...]]]"
[builtins fixtures/tuple.pyi]

[case testBanPathologicalRecursiveTuplesGeneric]
from typing import TypeVarTuple, Unpack

Ts = TypeVarTuple("Ts")
A = tuple[Unpack[B[Unpack[Ts]]]] # E: Invalid recursive alias: a tuple item of itself \
# E: Name "B" is used before definition
B = tuple[Unpack[A[Unpack[Ts]]]]
[builtins fixtures/tuple.pyi]

[case testBanTypeVarTupleNotImmediatelyInsideUnpack]
from typing import TypeVarTuple, Unpack

Ts = TypeVarTuple("Ts")
A = tuple[Unpack[tuple[Ts]]] # E: TypeVarTuple "Ts" is only valid with an unpack
x: A[int, str]
reveal_type(x) # N: Revealed type is "tuple[Any]"
[builtins fixtures/tuple.pyi]

[case testInferenceAgainstGenericVariadicWithBadType]
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.