summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2024-04-04 11:04:16 (GMT)
committerGitHub <noreply@github.com>2024-04-04 11:04:16 (GMT)
commitb5e12aa9ff581dd677d9b5f7adeb672cfb52068e (patch)
treea3db065d9d6e24d4fb7beaab2a37599e8ffc0050
parent14aef56ebbf3788e60427a9bfbd6de4713967ca0 (diff)
downloadcpython-b5e12aa9ff581dd677d9b5f7adeb672cfb52068e.zip
cpython-b5e12aa9ff581dd677d9b5f7adeb672cfb52068e.tar.gz
cpython-b5e12aa9ff581dd677d9b5f7adeb672cfb52068e.tar.bz2
[3.12] gh-117521: Improve typing.TypeGuard docstring (GH-117522) (#117538)
(cherry picked from commit b32789ccb91bbe43e88193f68b1364a8da6d9866) Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
-rw-r--r--Lib/typing.py25
1 files changed, 14 insertions, 11 deletions
diff --git a/Lib/typing.py b/Lib/typing.py
index c9962b9..b58c2d3 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -846,22 +846,25 @@ def TypeGuard(self, parameters):
2. If the return value is ``True``, the type of its argument
is the type inside ``TypeGuard``.
- For example::
+ For example::
+
+ def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
+ '''Determines whether all objects in the list are strings'''
+ return all(isinstance(x, str) for x in val)
- def is_str(val: Union[str, float]):
- # "isinstance" type guard
- if isinstance(val, str):
- # Type of ``val`` is narrowed to ``str``
- ...
- else:
- # Else, type of ``val`` is narrowed to ``float``.
- ...
+ def func1(val: list[object]):
+ if is_str_list(val):
+ # Type of ``val`` is narrowed to ``list[str]``.
+ print(" ".join(val))
+ else:
+ # Type of ``val`` remains as ``list[object]``.
+ print("Not a list of strings!")
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
form of ``TypeA`` (it can even be a wider form) and this may lead to
type-unsafe results. The main reason is to allow for things like
- narrowing ``List[object]`` to ``List[str]`` even though the latter is not
- a subtype of the former, since ``List`` is invariant. The responsibility of
+ narrowing ``list[object]`` to ``list[str]`` even though the latter is not
+ a subtype of the former, since ``list`` is invariant. The responsibility of
writing type-safe type guards is left to the user.
``TypeGuard`` also works with type variables. For more information, see