Skip to content

Commit b32789c

Browse files
gh-117521: Improve typing.TypeGuard docstring (#117522)
1 parent 3f5bcc8 commit b32789c

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

Lib/typing.py

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

0 commit comments

Comments
 (0)