Skip to content

Fix crash on TypeVar with a Callable bound or default referring to itself - #22341

Closed
waw666waw666 wants to merge 1 commit into
python:masterfrom
waw666waw666:fix-typevar-self-referential-callable-bound
Closed

waw666waw666 wants to merge 1 commit into
python:masterfrom
waw666waw666:fix-typevar-self-referential-callable-bound

Conversation

@waw666waw666

Copy link
Copy Markdown

Fixes #16940

T = TypeVar("T", bound=Callable[..., "T"]) crashes mypy with infinite recursion (a segfault when compiled). Unlike e.g. bound=list["T"], which is reported as a cyclic definition, Callable binds the free type variable T itself, so after the second semantic analysis pass the stored bound is def [T <: ...] (...) -> T. Re-analysing that bound on the next pass re-binds T from its own TypeVarExpr, whose bound is that same callable, and anal_var_def() never terminates. The same happens with default=Callable[..., "T"].

This PR makes process_typevar_declaration() detect a bound or default that refers to the type variable being defined, and reports the same Cannot resolve name "T" (possible cyclic definition) error used for the non-Callable case, replacing the bound/default with Any.

Added test cases for both the bound and the default; both crash on master and pass with this change. Bounds that use a different type variable inside a Callable (e.g. bound=Callable[[S], S]) are unaffected.

@github-actions

github-actions Bot commented Nov 1, 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.

Segmentation fault for TypeVar("T", bound=Callable[..., "T"])

2 participants