Skip to content

Fix crash on self-referential Generic base - #22046

Draft
Dextheking1 wants to merge 1 commit into
python:masterfrom
Dextheking1:fix-generic-self-base
Draft

Dextheking1 wants to merge 1 commit into
python:masterfrom
Dextheking1:fix-generic-self-base

Conversation

@Dextheking1

Copy link
Copy Markdown

Fixes #21549.

class C(Generic[C]) crashed with "AssertionError: Must not defer during final iteration". The placeholder for C can never resolve (the class is still being defined), so the deferral in analyze_unbound_tvar_impl looped until the final iteration and hit the assert.

Changed analyze_unbound_tvar_impl in mypy/semanal.py to not defer on the final iteration when the looked-up symbol is still a placeholder. It falls through and the caller reports "Free type variable expected in Generic[...]" plus "Cannot resolve name" instead of crashing. This matches the existing convention that defer() must never run on the final iteration.

Verified:

  • class C(Generic[C]) and class E(Generic["E"]) no longer crash, both now report errors.
  • Forward-declared TypeVars (class D(Generic[T]) with T defined later) still resolve, no new errors.
  • New regression test testSelfReferenceInGenericBase in test-data/unit/semanal-errors.test.
  • mypy/test/testsemanal.py: 578 passed.
  • mypy/test/testcheck.py (generics, classes, protocols, typevar-tuple suites): 1159 passed, 3 skipped, 1 xfailed.
  • mypy self-check on mypy/semanal.py: clean.

class C(Generic[C]) hit "AssertionError: Must not defer during final
iteration" because the placeholder for C never resolves. On the final
iteration, report an error instead of deferring, matching how other
placeholder sites behave. Adds a regression test.
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.

AssertionError: Must not defer during final iteration with recursive class definition

1 participant