Skip to content

Commit dd25f94

Browse files
committed
stubtest: don't flag __class_getitem__ missing for PEP 695 generic stubs
PEP 695 generic syntax (class Foo[T]: ...) implicitly provides __class_getitem__ at runtime. When a stub uses this syntax and the runtime class defines __class_getitem__ explicitly, stubtest was incorrectly reporting it as missing from the stub. Fix: in verify_typeinfo(), discard "__class_getitem__" from the set of attributes to check when the stub class has PEP 695 type parameters (ClassDef.type_args is not None). Fixes: #21253
1 parent dee7b3d commit dd25f94

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

mypy/stubtest.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,10 @@ def verify_typeinfo(
700700
to_check.discard("__init__")
701701
if is_runtime_typeddict:
702702
to_check.discard("__new__")
703+
# PEP 695 generic syntax (class Foo[T]: ...) implicitly provides __class_getitem__
704+
# at runtime, so don't require an explicit stub definition.
705+
if stub.defn.type_args is not None:
706+
to_check.discard("__class_getitem__")
703707

704708
for entry in sorted(to_check):
705709
mangled_entry = entry

mypy/test/teststubtest.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1825,6 +1825,19 @@ def test_dunders(self) -> Iterator[Case]:
18251825
runtime="class D:\n def __class_getitem__(cls, type): ...",
18261826
error=None,
18271827
)
1828+
if sys.version_info >= (3, 12):
1829+
# PEP 695 generic syntax implicitly provides __class_getitem__ at runtime
1830+
yield Case(
1831+
stub="class D2[T]: ...",
1832+
runtime="class D2:\n def __class_getitem__(cls, _): return cls",
1833+
error=None,
1834+
)
1835+
# Non-generic stub still reports missing __class_getitem__
1836+
yield Case(
1837+
stub="class D3: ...",
1838+
runtime="class D3:\n def __class_getitem__(cls, _): return cls",
1839+
error="D3.__class_getitem__",
1840+
)
18281841
yield Case(
18291842
stub="class E:\n def __getitem__(self, item: object) -> object: ...",
18301843
runtime="class E:\n def __getitem__(self, item: object, /) -> object: ...",

0 commit comments

Comments
 (0)