Skip to content

Handle expanding recursive protocol returns - #21787

Open
Rishav23av wants to merge 1 commit into
python:masterfrom
Rishav23av:fix/21739-protocol-recursion
Open

Handle expanding recursive protocol returns#21787
Rishav23av wants to merge 1 commit into
python:masterfrom
Rishav23av:fix/21739-protocol-recursion

Conversation

@Rishav23av

Copy link
Copy Markdown

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 compiled
build).

This adds a deliberately narrow cycle closure for the safe case where:

  • the exact protocol instance has already been seen with the same candidate class
  • there is one non-settable, non-overloaded callable member
  • both sides return themselves directly
  • the candidate's non-return signature does not depend on its class type variables

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] to P[object] before reaching a fixed point.
The latter ensures the new shortcut does not skip a changing argument
obligation.

Validation:

  • python runtests.py self lint
  • complete check-protocols.test: 202 passed, 1 skipped
  • focused recursive-protocol group: 8 passed
  • original reduced CLI reproduction: clean

Disclosure: 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.

@github-actions

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.

Endless call cycle between is_callable_compatible and is_protocol_implementation

1 participant