summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAdrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>2022-08-30 14:57:03 (GMT)
committerGitHub <noreply@github.com>2022-08-30 14:57:03 (GMT)
commit07f12b5c1567581aa77d523e462b0e7f75c1f05c (patch)
treee28eee970a97d50dfc80af09dbb0fa084a33d39c
parent22ed5233b76fe33f9767c6a5665608e7f398e7d7 (diff)
downloadcpython-07f12b5c1567581aa77d523e462b0e7f75c1f05c.zip
cpython-07f12b5c1567581aa77d523e462b0e7f75c1f05c.tar.gz
cpython-07f12b5c1567581aa77d523e462b0e7f75c1f05c.tar.bz2
gh-95337: update TypeVarTuple example (#95338)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
-rw-r--r--Doc/library/typing.rst21
1 files changed, 13 insertions, 8 deletions
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index c6dd697..0939973 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -1305,20 +1305,25 @@ These are not used in annotations. They are building blocks for creating generic
T = TypeVar('T')
Ts = TypeVarTuple('Ts')
- def remove_first_element(tup: tuple[T, *Ts]) -> tuple[*Ts]:
- return tup[1:]
+ def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
+ return (*tup[1:], tup[0])
# T is bound to int, Ts is bound to ()
- # Return value is (), which has type tuple[()]
- remove_first_element(tup=(1,))
+ # Return value is (1,), which has type tuple[int]
+ move_first_element_to_last(tup=(1,))
# T is bound to int, Ts is bound to (str,)
- # Return value is ('spam',), which has type tuple[str]
- remove_first_element(tup=(1, 'spam'))
+ # Return value is ('spam', 1), which has type tuple[str, int]
+ move_first_element_to_last(tup=(1, 'spam'))
# T is bound to int, Ts is bound to (str, float)
- # Return value is ('spam', 3.0), which has type tuple[str, float]
- remove_first_element(tup=(1, 'spam', 3.0))
+ # Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
+ 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]``.
Conceptually, you can think of ``Ts`` as a tuple of type variables