Skip to content

Commit d00a9e0

Browse files
gh-95337: update TypeVarTuple example (GH-95338)
Co-authored-by: Alex Waygood <[email protected]> (cherry picked from commit 07f12b5) Co-authored-by: Adrian Garcia Badaracco <[email protected]>
1 parent a1671a9 commit d00a9e0

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

Doc/library/typing.rst

+13-8
Original file line numberDiff line numberDiff line change
@@ -1305,20 +1305,25 @@ These are not used in annotations. They are building blocks for creating generic
13051305
T = TypeVar('T')
13061306
Ts = TypeVarTuple('Ts')
13071307

1308-
def remove_first_element(tup: tuple[T, *Ts]) -> tuple[*Ts]:
1309-
return tup[1:]
1308+
def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
1309+
return (*tup[1:], tup[0])
13101310

13111311
# T is bound to int, Ts is bound to ()
1312-
# Return value is (), which has type tuple[()]
1313-
remove_first_element(tup=(1,))
1312+
# Return value is (1,), which has type tuple[int]
1313+
move_first_element_to_last(tup=(1,))
13141314

13151315
# T is bound to int, Ts is bound to (str,)
1316-
# Return value is ('spam',), which has type tuple[str]
1317-
remove_first_element(tup=(1, 'spam'))
1316+
# Return value is ('spam', 1), which has type tuple[str, int]
1317+
move_first_element_to_last(tup=(1, 'spam'))
13181318

13191319
# T is bound to int, Ts is bound to (str, float)
1320-
# Return value is ('spam', 3.0), which has type tuple[str, float]
1321-
remove_first_element(tup=(1, 'spam', 3.0))
1320+
# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
1321+
move_first_element_to_last(tup=(1, 'spam', 3.0))
1322+
1323+
# This fails to type check (and fails at runtime)
1324+
# because tuple[()] is not compatible with tuple[T, *Ts]
1325+
# (at least one element is required)
1326+
move_first_element_to_last(tup=())
13221327

13231328
Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``.
13241329
Conceptually, you can think of ``Ts`` as a tuple of type variables

0 commit comments

Comments
 (0)