2Tests TypeVars with upper bounds.
5# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound
7from typing import Collection, Generic, Sized, TypeVar, assert_type
9# > A type variable may specify an upper bound using bound=<type>
11T_Good1 = TypeVar("T_Good1", bound=int) # OK
12T_Good2 = TypeVar("T_Good2", bound="ForwardRef | str") # OK
18# > <type> itself cannot be parameterized by type variables.
23class Test(Generic[T]):
24 T_Bad1 = TypeVar("T_Bad1", bound=list[T]) # E
[invalid-type-variable-bound] TypeVar upper bound cannot be generic
27ST = TypeVar("ST", bound=Sized)
30def longer(x: ST, y: ST) -> ST:
37def f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):
38 assert_type(longer(list1, list2), list[int])
39 assert_type(longer(set1, set2), set[int])
41 # Either answer here is conformant with the spec;
42 # exactly one should pass:
43 assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]
44 assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]
Tag 'mixed-collections'
[type-assertion-failure] Type `list[int] | set[int]` does not match asserted type `Collection[int]`
47def requires_collection(c: Collection[int]) -> None: ...
50requires_collection(longer([1], [1, 2])) # OK
[invalid-argument-type] Argument to function `longer` is incorrect: Argument type `Literal[3]` does not satisfy upper bound `Sized` of type variable `ST`
[invalid-argument-type] Argument to function `longer` is incorrect: Argument type `Literal[3]` does not satisfy upper bound `Sized` of type variable `ST`
55# > An upper bound cannot be combined with type constraints
57T_Bad2 = TypeVar("T_Bad2", str, int, bound="int") # E
[invalid-legacy-type-variable] A `TypeVar` cannot have both a bound and constraints