← Back to index

generics_syntax_declarations.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 10
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Validates the type parameter syntax introduced in PEP 695.
3"""
4
5# Specification: https://peps.python.org/pep-0695/#type-parameter-declarations
6
7
8# This generic class is parameterized by a TypeVar T, a
9# TypeVarTuple Ts, and a ParamSpec P.
10from typing import Generic, Protocol
13class ChildClass[T, *Ts, **P]:
14 pass
17class ClassA[T](Generic[T]): # E: Runtime error
[invalid-generic-class] Cannot both inherit from `typing.Generic` and use PEP 695 type variables
18 ...
21class ClassB[S, T](Protocol): # OK
22 ...
25class ClassC[S, T](Protocol[S, T]): # E
[invalid-generic-class] Cannot both inherit from subscripted `Protocol` and use PEP 695 type variables
26 ...
29class ClassD[T: str]:
30 def method1(self, x: T):
31 x.capitalize() # OK
32 x.is_integer() # E
[unresolved-attribute] Object of type `T@ClassD` has no attribute `is_integer`
35class ClassE[T: dict[str, int]]: # OK
36 pass
39class ClassF[S: ForwardReference[int], T: "ForwardReference[str]"]: # OK
40 ...
43class ClassG[V]:
44 class ClassD[T: dict[str, V]]: # E: generic type not allowed
[invalid-type-variable-bound] TypeVar upper bound cannot be generic
45 ...
48class ClassH[T: [str, int]]: # E: illegal expression form
[invalid-type-form] List literals are not allowed in this context in a type expression: Did you mean `tuple[str, int]`?
49 ...
52class ClassI[AnyStr: (str, bytes)]: # OK
53 ...
56class ClassJ[T: (ForwardReference[int], "ForwardReference[str]", bytes)]: # OK
57 ...
60class ClassK[T: ()]: # E: two or more types required
[invalid-type-variable-constraints] TypeVar must have at least two constrained types
61 ...
64class ClassL[T: (str,)]: # E: two or more types required
[invalid-type-variable-constraints] TypeVar must have at least two constrained types
65 ...
68t1 = (bytes, str)
71class ClassM[T: t1]: # E: literal tuple expression required
[invalid-type-form] Variable of type `tuple[<class 'bytes'>, <class 'str'>]` is not allowed in a type expression
72 ...
75class ClassN[T: (3, bytes)]: # E: invalid expression form
[invalid-type-form] Int literals are not allowed in this context in a type expression
76 ...
79class ClassO[T: (list[S], str)]: # E: generic type
[unresolved-reference] Name `S` used when not defined
80 ...
83class ForwardReference[T]: ...