Skip to content

stubtest: don't flag __class_getitem__ as missing on a generic stub#21582

Open
ShirGanon wants to merge 1 commit into
python:masterfrom
ShirGanon:fix/stubtest-class-getitem-generic
Open

stubtest: don't flag __class_getitem__ as missing on a generic stub#21582
ShirGanon wants to merge 1 commit into
python:masterfrom
ShirGanon:fix/stubtest-class-getitem-generic

Conversation

@ShirGanon
Copy link
Copy Markdown

Fixes #21253

A class that implements __class_getitem__ at runtime (to make itself subscriptable) is correctly modelled in a stub by declaring the class as generic — either with PEP 695 syntax (class C[T]) or Generic[T]. stubtest, however, reported a false positive in that case:

error: C.__class_getitem__ is not present in stub

verify_typeinfo iterates the runtime class members and, finding __class_getitem__ on the runtime class with no counterpart in the (generic) stub, flagged it as missing.

Change

In verify_typeinfo, skip the __class_getitem__ runtime member when the stub class is generic (TypeInfo.is_generic()) and does not explicitly declare it — the generic type parameters already express that subscriptability at the type level. A non-generic stub that omits a runtime __class_getitem__ is still reported as before, so the change only suppresses the false positive.

Testing

  • Added test_class_getitem_on_generic in mypy/test/teststubtest.py with two cases:
    • generic stub (Generic[T]) + runtime __class_getitem__no error;
    • non-generic stub + runtime __class_getitem__ → still reports __class_getitem__ is not present in stub.
  • Verified the new test fails without the stubtest.py change and passes with it.
  • Full mypy/test/teststubtest.py suite passes (68 tests), no regressions.
  • black, ruff, and mypy self-check on mypy/stubtest.py are clean.

(I used the Generic[T] form in the test rather than PEP 695 class C[T] so the stub parses on all supported Python versions; the fix covers both, since both make TypeInfo.is_generic() true.)

Disclosure: drafted with Claude Code; reviewed, understood, and tested locally.

A class that implements `__class_getitem__` at runtime to support
subscription is correctly modelled in a stub by declaring the class as
generic (PEP 695 `class C[T]` or `Generic[T]`). stubtest nevertheless
reported `C.__class_getitem__ is not present in stub` in that case.

Skip the `__class_getitem__` runtime member when the stub class is generic
(`TypeInfo.is_generic()`) and does not explicitly declare it. Non-generic
stubs still report the missing method as before.

Fixes python#21253
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.

stubtest false positive when __class_getitem__ is implemented in class body and corresponding body in stub is generic

1 participant