← Back to index

tuples_unpacked.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 3
FP: 0
FN: 3
Optional: 0 / 0
1"""
2Tests the handling of unpacked tuples embedded within other tuples.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#unpacked-tuple-form
6
7# > An unpacked form of ``tuple`` (using an unpack operator ``*``)
8# > can be used within a tuple type argument list
9
10# > Unpacking a concrete tuple type is analogous to unpacking a tuple of values at runtime.
13from typing import TypeVarTuple, Unpack, assert_type
16def func1(x: tuple[int, *tuple[bool, bool], str]):
17 assert_type(x, tuple[int, bool, bool, str])
18 assert_type(x, tuple[*tuple[int, bool], bool, str])
19 assert_type(x, tuple[int, bool, *tuple[bool, str]])
22# > Unpacking an unbounded tuple preserves the unbounded tuple as it is.
25def func2(x: tuple[int, *tuple[bool, ...], str]):
26 assert_type(x, tuple[int, *tuple[bool, ...], str])
29# > For example, tuple[int, *tuple[str]] is equivalent to tuple[int, str].
31u1: tuple[*tuple[int], *tuple[int]] = (int(1), int(1)) # OK
32assert_type(u1, tuple[int, int])
33u2: tuple[*tuple[int, ...], *tuple[int]] # OK
36# > Only one unbounded tuple can be used within another tuple:
38t1: tuple[*tuple[str], *tuple[str]] # OK
39t2: tuple[*tuple[str, *tuple[str, ...]]] # OK
40t3: tuple[*tuple[str, ...], *tuple[int, ...]] # E
[invalid-type-form] Multiple unpacked variadic tuples are not allowed in a `tuple` specialization
41t4: tuple[*tuple[str, *tuple[str, ...]], *tuple[int, ...]] # E
[invalid-type-form] Multiple unpacked variadic tuples are not allowed in a `tuple` specialization
44# > An unpacked TypeVarTuple counts as an unbounded tuple in the context of this rule
46Ts = TypeVarTuple("Ts")
49def func3(t: tuple[*Ts]):
50 t5: tuple[*tuple[str], *Ts] # OK
51 t6: tuple[*tuple[str, ...], *Ts] # E
[invalid-type-form] Multiple unpacked variadic tuples are not allowed in a `tuple` specialization
54# > The ``*`` syntax requires Python 3.11 or newer. For older versions of Python,
55# > the ``typing.Unpack`` special form can be used:
57t11: tuple[Unpack[tuple[str]], Unpack[tuple[str]]] # OK
58t12: tuple[Unpack[tuple[str, Unpack[tuple[str, ...]]]]] # OK
59t13: tuple[Unpack[tuple[str, ...]], Unpack[tuple[int, ...]]] # E
Expected a ty diagnostic for this line
60t14: tuple[ # E[t14]
Expected a ty diagnostic for this line (tag 't14')
61 Unpack[tuple[str, Unpack[tuple[str, ...]]]], Unpack[tuple[int, ...]] # E[t14]
Expected a ty diagnostic for this line (tag 't14')
62]