-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathgenerics_upper_bound.py
More file actions
57 lines (31 loc) · 1.35 KB
/
generics_upper_bound.py
File metadata and controls
57 lines (31 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
Tests TypeVars with upper bounds.
"""
# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound
from typing import Collection, Generic, Sized, TypeVar, assert_type
# > A type variable may specify an upper bound using bound=<type>
T_Good1 = TypeVar("T_Good1", bound=int) # OK
T_Good2 = TypeVar("T_Good2", bound="ForwardRef | str") # OK
class ForwardRef: ...
# > <type> itself cannot be parameterized by type variables.
T = TypeVar("T")
class Test(Generic[T]):
T_Bad1 = TypeVar("T_Bad1", bound=list[T]) # E
ST = TypeVar("ST", bound=Sized)
def longer(x: ST, y: ST) -> ST:
if len(x) > len(y):
return x
else:
return y
def f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):
assert_type(longer(list1, list2), list[int])
assert_type(longer(set1, set2), set[int])
# Either answer here is conformant with the spec;
# exactly one should pass:
assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]
assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]
def requires_collection(c: Collection[int]) -> None: ...
requires_collection(longer([1], [1, 2])) # OK
longer(3, 3) # E
# > An upper bound cannot be combined with type constraints
T_Bad2 = TypeVar("T_Bad2", str, int, bound="int") # E