← Back to index
generics_defaults_specialization.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 1
FP: 0
FN: 1
Optional: 0 / 0
1
"""
2
Tests
for
specialization
rules
associated
with
type
parameters
with
3
default
values
.
4
"""
5
6
# > A generic type alias can be further subscripted following normal subscription
7
# > rules. If a type parameter has a default that hasn't been overridden, it should
8
# > be treated like it was substituted into the type alias.
9
10
from
typing
import
Generic
,
TypeAlias
,
assert_type
11
from
typing_extensions
import
TypeVar
12
13
T1
=
TypeVar
(
"T1"
)
14
T2
=
TypeVar
(
"T2"
)
15
DefaultIntT
=
TypeVar
(
"DefaultIntT"
,
default
=
int
)
16
DefaultStrT
=
TypeVar
(
"DefaultStrT"
,
default
=
str
)
17
18
19
class
SomethingWithNoDefaults
(
Generic
[
T1
,
T2
]):
...
20
21
22
MyAlias
:
TypeAlias
=
SomethingWithNoDefaults
[
int
,
DefaultStrT
]
# OK
23
24
25
def
func1
(
p1
:
MyAlias
,
p2
:
MyAlias
[
bool
]):
26
assert_type
(
p1
,
SomethingWithNoDefaults
[
int
,
str
])
27
assert_type
(
p2
,
SomethingWithNoDefaults
[
int
,
bool
])
28
29
30
MyAlias
[
bool
,
int
]
# E: too many arguments passed to MyAlias
[invalid-type-arguments] Too many type arguments: expected between 0 and 1, got 2
31
32
33
# > Generic classes with type parameters that have defaults behave similarly
34
# > generic type aliases. That is, subclasses can be further subscripted following
35
# > normal subscription rules, non-overridden defaults should be substituted.
36
37
38
class
SubclassMe
(
Generic
[
T1
,
DefaultStrT
]):
39
x
:
DefaultStrT
40
41
42
class
Bar
(
SubclassMe
[
int
,
DefaultStrT
]):
...
43
44
45
assert_type
(
Bar
,
type
[
Bar
[
str
]])
46
assert_type
(
Bar
(),
Bar
[
str
])
47
assert_type
(
Bar
[
bool
](),
Bar
[
bool
])
48
49
50
class
Foo
(
SubclassMe
[
float
]):
...
51
52
53
assert_type
(
Foo
()
.
x
,
str
)
54
55
Foo
[
str
]
# E: Foo cannot be further subscripted
Expected a ty diagnostic for this line
56
57
58
class
Baz
(
Generic
[
DefaultIntT
,
DefaultStrT
]):
...
59
60
61
class
Spam
(
Baz
):
...
62
63
64
# Spam is <subclass of Baz[int, str]>
65
v1
:
Baz
[
int
,
str
]
=
Spam
()