Handle expanding recursive protocol returns - #21787
Open
Rishav23av wants to merge 1 commit into
Open
Conversation
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 #21739.
The recursive protocol assumption stack currently closes only when the exact
candidate and protocol instances repeat. That does not happen when a callable
returns a strictly larger instance of its own generic class, so the subtype
check keeps alternating between callable compatibility and protocol
implementation until it raises
RecursionError(or segfaults in a compiledbuild).
This adds a deliberately narrow cycle closure for the safe case where:
Those conditions keep every non-return obligation unchanged while the candidate
return grows. Broader recursive shapes continue through the existing path.
The tests include the reported expanding-return case and a negative case where
the protocol changes from
P[int]toP[object]before reaching a fixed point.The latter ensures the new shortcut does not skip a changing argument
obligation.
Validation:
python runtests.py self lintcheck-protocols.test: 202 passed, 1 skippedDisclosure: I developed this change with assistance from Claude Code and Codex.
I reviewed the implementation, challenged several unsafe approaches with
counterexamples, and ran the checks listed above.