Skip to content

Commit b5e12aa

Browse files
[3.12] gh-117521: Improve typing.TypeGuard docstring (GH-117522) (#117538)
(cherry picked from commit b32789c) Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent 14aef56 commit b5e12aa

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

Lib/typing.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -846,22 +846,25 @@ def TypeGuard(self, parameters):
846846
2. If the return value is ``True``, the type of its argument
847847
is the type inside ``TypeGuard``.
848848
849-
For example::
849+
For example::
850+
851+
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
852+
'''Determines whether all objects in the list are strings'''
853+
return all(isinstance(x, str) for x in val)
850854
851-
def is_str(val: Union[str, float]):
852-
# "isinstance" type guard
853-
if isinstance(val, str):
854-
# Type of ``val`` is narrowed to ``str``
855-
...
856-
else:
857-
# Else, type of ``val`` is narrowed to ``float``.
858-
...
855+
def func1(val: list[object]):
856+
if is_str_list(val):
857+
# Type of ``val`` is narrowed to ``list[str]``.
858+
print(" ".join(val))
859+
else:
860+
# Type of ``val`` remains as ``list[object]``.
861+
print("Not a list of strings!")
859862
860863
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
861864
form of ``TypeA`` (it can even be a wider form) and this may lead to
862865
type-unsafe results. The main reason is to allow for things like
863-
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
864-
a subtype of the former, since ``List`` is invariant. The responsibility of
866+
narrowing ``list[object]`` to ``list[str]`` even though the latter is not
867+
a subtype of the former, since ``list`` is invariant. The responsibility of
865868
writing type-safe type guards is left to the user.
866869
867870
``TypeGuard`` also works with type variables. For more information, see

0 commit comments

Comments
 (0)