← Back to index

generics_typevartuple_args.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 3
FN: 9
Optional: 0 / 0
1"""
2Tests for the use of TypeVarTuple with "*args" parameter.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#args-as-a-type-variable-tuple
6
7# > If *args is annotated as a type variable tuple, the types of the individual
8# > arguments become the types in the type variable tuple.
9
10from typing import TypeVarTuple, assert_type
13Ts = TypeVarTuple("Ts")
16def args_to_tuple(*args: *Ts) -> tuple[*Ts]:
17 raise NotImplementedError
20assert_type(args_to_tuple(1, "a"), tuple[int, str])
Unexpected error [type-assertion-failure] Type `tuple[int, str]` does not match asserted type `tuple[@Todo(TypeVarTuple), ...]`
23class Env:
24 ...
27def exec_le(path: str, *args: * tuple[*Ts, Env], env: Env | None = None) -> tuple[*Ts]:
28 raise NotImplementedError
31assert_type(exec_le("", Env()), tuple[()]) # OK
Unexpected error [type-assertion-failure] Type `tuple[()]` does not match asserted type `tuple[@Todo(TypeVarTuple), ...]`
32assert_type(exec_le("", 0, "", Env()), tuple[int, str]) # OK
Unexpected error [type-assertion-failure] Type `tuple[int, str]` does not match asserted type `tuple[@Todo(TypeVarTuple), ...]`
33exec_le("", 0, "") # E
Expected a ty diagnostic for this line
34exec_le("", 0, "", env=Env()) # E
Expected a ty diagnostic for this line
37# > Using an unpacked unbounded tuple is equivalent to the
38# > PEP 484#arbitrary-argument-lists-and-default-argument-values behavior of
39# > *args: int, which accepts zero or more values of type int.
42def func1(*args: * tuple[int, ...]) -> None:
43 ...
46func1() # OK
47func1(1, 2, 3, 4, 5) # OK
48func1(1, "2", 3) # E
Expected a ty diagnostic for this line
51def func2(*args: * tuple[int, *tuple[str, ...], str]) -> None:
52 ...
55func2(1, "") # OK
56func2(1, "", "", "", "") # OK
57func2(1, 1, "") # E
Expected a ty diagnostic for this line
58func2(1) # E
Expected a ty diagnostic for this line
59func2("") # E
Expected a ty diagnostic for this line
62def func3(*args: * tuple[int, str]) -> None:
63 ...
66func3(1, "hello") # OK
67func3(1) # E
Expected a ty diagnostic for this line
70def func4(*args: tuple[*Ts]):
71 ...
74func4((0,), (1,)) # OK
75func4((0,), (1, 2)) # E
Expected a ty diagnostic for this line
76func4((0,), ("1",)) # E
Expected a ty diagnostic for this line
79# This is a syntax error, so leave it commented out.
80# def func5(**kwargs: *Ts): # E
81# ...