Repository navigation
Fix crash on contravariant base that refers back to the subclass - #22365
Closed
kushwahaamar-dev wants to merge 1 commit into
Closed
kushwahaamar-dev wants to merge 1 commit into
kushwahaamar-dev wants to merge 1 commit into
Conversation
With class C(N[N[C]]) and a contravariant N, checking C <: N[C] maps C to N[N[C]], and the contravariant argument flips the check back to C <: N[C], so mypy recursed until it crashed. Assume the pair holds while checking type arguments when left was mapped to a base and the target has a contravariant (or not yet inferred) type variable. That reuses the existing assumption stack that recursive type aliases already rely on. Fixes python#22360
Contributor
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Fixes #22360
With a contravariant
Nandchecking
C <: N[C]mapsCup toN[N[C]], and sinceNis contravariant the argument check becomesC <: N[C]again. mypy kept going around that loop until it hit the recursion limit (segfault on compiled builds).is_subtypealready checks the assumption stack at the top, which is how recursive aliases avoid this. So invisit_instanceI push(left, right)while checking the type args, but only whenleftwas mapped to a base class and the target has a contravariant (or not yet inferred) type var. That's the only shape that can loop back, and it keeps the extra work off the common path.Cis now accepted as anN[C], which matches pyright and ty. A real mismatch like returningCasN[int]still errors.Added tests for the plain and generic versions from the issue, plus a PEP 695 one where the variance is inferred.