← 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"""
2Tests 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
9from typing import Generic, NewType, TypeVar, TypeVarTuple, assert_type
12Height = NewType("Height", int)
13Width = NewType("Width", int)
14Batch = NewType("Batch", int)
15Channels = NewType("Channels", int)
17Shape = TypeVarTuple("Shape")
18Ts = TypeVarTuple("Ts")
19T = TypeVar("T")
22class Array(Generic[*Ts]):
23 ...
26def add_batch_axis(x: Array[*Shape]) -> Array[Batch, *Shape]:
27 raise NotImplementedError
30def del_batch_axis(x: Array[Batch, *Shape]) -> Array[*Shape]:
31 raise NotImplementedError
34def add_batch_channels(x: Array[*Shape]) -> Array[Batch, *Shape, Channels]:
35 raise NotImplementedError
38def 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])
47def prefix_tuple(x: T, y: tuple[*Ts]) -> tuple[T, *Ts]:
48 raise NotImplementedError
51z = prefix_tuple(x=0, y=(True, "a"))
52assert_type(z, tuple[int, bool, str])
Unexpected error [type-assertion-failure] Type `tuple[int, bool, str]` does not match asserted type `tuple[@Todo(TypeVarTuple), ...]`
55def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
56 return (*tup[1:], tup[0])