← Back to index

tuples_type_form.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 11
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the handling of builtins.tuple.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#tuple-type-form
6
7# > The type of a tuple can be expressed by listing the element types.
8from typing import Literal
9
11t1: tuple[int] = (1,) # OK
12t1 = (1, 2) # E
[invalid-assignment] Object of type `tuple[Literal[1], Literal[2]]` is not assignable to `tuple[int]`
13t2: tuple[int, int] = (1, 2) # OK
14t2 = (1,) # E
[invalid-assignment] Object of type `tuple[Literal[1]]` is not assignable to `tuple[int, int]`
15t2 = (1, "") # E
[invalid-assignment] Object of type `tuple[Literal[1], Literal[""]]` is not assignable to `tuple[int, int]`
18def func1() -> tuple[Literal[1], Literal[2]]:
19 return (1, 2)
22# > The empty tuple can be typed as tuple[()].
24t10: tuple[()] = () # OK
25t10 = (1,) # E
[invalid-assignment] Object of type `tuple[Literal[1]]` is not assignable to `tuple[()]`
28def func2() -> list[tuple[()]]:
29 return [(), (), ()]
32# > Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis.
33t20: tuple[int, ...] = () # OK
34t20 = (1,) # OK
35t20 = (1, 2, 3, 4) # OK
36t20 = (1, 2, 3, "") # E
[invalid-assignment] Object of type `tuple[Literal[1], Literal[2], Literal[3], Literal[""]]` is not assignable to `tuple[int, ...]`
39t30: tuple[int, ...] # OK
40t31: tuple[int, int, ...] # E
[invalid-type-form] Invalid `tuple` specialization: `...` can only be used as the second element in a two-element `tuple` specialization
41t32: tuple[...] # E
[invalid-type-form] Invalid `tuple` specialization: `...` can only be used as the second element in a two-element `tuple` specialization
42t33: tuple[..., int] # E
[invalid-type-form] Invalid `tuple` specialization: `...` can only be used as the second element in a two-element `tuple` specialization
43t34: tuple[int, ..., int] # E
[invalid-type-form] Invalid `tuple` specialization: `...` can only be used as the second element in a two-element `tuple` specialization
44t35: tuple[*tuple[str], ...] # E
[invalid-type-form] Invalid `tuple` specialization: `...` cannot be used after an unpacked element
45t36: tuple[*tuple[str, ...], ...] # E
[invalid-type-form] Invalid `tuple` specialization: `...` cannot be used after an unpacked element