← Back to index
generics_typevartuple_concat.py
True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 1
FN: 0
Optional: 0 / 0
1
"""
2
Tests
type
concatenation
using
TypeVarTuples
.
3
"""
4
5
# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-concatenation
6
7
# > Type variable tuples don’t have to be alone; normal types can be prefixed and/or suffixed.
8
9
from
typing
import
Generic
,
NewType
,
TypeVar
,
TypeVarTuple
,
assert_type
10
11
12
Height
=
NewType
(
"Height"
,
int
)
13
Width
=
NewType
(
"Width"
,
int
)
14
Batch
=
NewType
(
"Batch"
,
int
)
15
Channels
=
NewType
(
"Channels"
,
int
)
16
17
Shape
=
TypeVarTuple
(
"Shape"
)
18
Ts
=
TypeVarTuple
(
"Ts"
)
19
T
=
TypeVar
(
"T"
)
20
21
22
class
Array
(
Generic
[
*
Ts
]):
23
...
24
25
26
def
add_batch_axis
(
x
:
Array
[
*
Shape
])
->
Array
[
Batch
,
*
Shape
]:
27
raise
NotImplementedError
28
29
30
def
del_batch_axis
(
x
:
Array
[
Batch
,
*
Shape
])
->
Array
[
*
Shape
]:
31
raise
NotImplementedError
32
33
34
def
add_batch_channels
(
x
:
Array
[
*
Shape
])
->
Array
[
Batch
,
*
Shape
,
Channels
]:
35
raise
NotImplementedError
36
37
38
def
func1
(
a
:
Array
[
Height
,
Width
]):
39
b
=
add_batch_axis
(
a
)
# OK
40
assert_type
(
b
,
Array
[
Batch
,
Height
,
Width
])
41
c
=
del_batch_axis
(
b
)
# OK
42
assert_type
(
c
,
Array
[
Height
,
Width
])
43
d
=
add_batch_channels
(
a
)
# OK
44
assert_type
(
d
,
Array
[
Batch
,
Height
,
Width
,
Channels
])
45
46
47
def
prefix_tuple
(
x
:
T
,
y
:
tuple
[
*
Ts
])
->
tuple
[
T
,
*
Ts
]:
48
raise
NotImplementedError
49
50
51
z
=
prefix_tuple
(
x
=
0
,
y
=
(
True
,
"a"
))
52
assert_type
(
z
,
tuple
[
int
,
bool
,
str
])
Unexpected error [type-assertion-failure] Type `tuple[int, bool, str]` does not match asserted type `tuple[@Todo(TypeVarTuple), ...]`
53
54
55
def
move_first_element_to_last
(
tup
:
tuple
[
T
,
*
Ts
])
->
tuple
[
*
Ts
,
T
]:
56
return
(
*
tup
[
1
:],
tup
[
0
])