gh-95337: update TypeVarTuple example (#95338)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
parent
22ed5233b7
commit
07f12b5c15
@ -1305,20 +1305,25 @@ These are not used in annotations. They are building blocks for creating generic
|
|||||||
T = TypeVar('T')
|
T = TypeVar('T')
|
||||||
Ts = TypeVarTuple('Ts')
|
Ts = TypeVarTuple('Ts')
|
||||||
|
|
||||||
def remove_first_element(tup: tuple[T, *Ts]) -> tuple[*Ts]:
|
def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
|
||||||
return tup[1:]
|
return (*tup[1:], tup[0])
|
||||||
|
|
||||||
# T is bound to int, Ts is bound to ()
|
# T is bound to int, Ts is bound to ()
|
||||||
# Return value is (), which has type tuple[()]
|
# Return value is (1,), which has type tuple[int]
|
||||||
remove_first_element(tup=(1,))
|
move_first_element_to_last(tup=(1,))
|
||||||
|
|
||||||
# T is bound to int, Ts is bound to (str,)
|
# T is bound to int, Ts is bound to (str,)
|
||||||
# Return value is ('spam',), which has type tuple[str]
|
# Return value is ('spam', 1), which has type tuple[str, int]
|
||||||
remove_first_element(tup=(1, 'spam'))
|
move_first_element_to_last(tup=(1, 'spam'))
|
||||||
|
|
||||||
# T is bound to int, Ts is bound to (str, float)
|
# T is bound to int, Ts is bound to (str, float)
|
||||||
# Return value is ('spam', 3.0), which has type tuple[str, float]
|
# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
|
||||||
remove_first_element(tup=(1, 'spam', 3.0))
|
move_first_element_to_last(tup=(1, 'spam', 3.0))
|
||||||
|
|
||||||
|
# This fails to type check (and fails at runtime)
|
||||||
|
# because tuple[()] is not compatible with tuple[T, *Ts]
|
||||||
|
# (at least one element is required)
|
||||||
|
move_first_element_to_last(tup=())
|
||||||
|
|
||||||
Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``.
|
Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``.
|
||||||
Conceptually, you can think of ``Ts`` as a tuple of type variables
|
Conceptually, you can think of ``Ts`` as a tuple of type variables
|
||||||
|
Loading…
x
Reference in New Issue
Block a user