Skip to content

Commit

Permalink
pythongh-117521: Improve typing.TypeGuard docstring
Browse files Browse the repository at this point in the history
  • Loading branch information
JelleZijlstra committed Apr 3, 2024
1 parent c43f6a4 commit 1ac193c
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,22 +841,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
Expand Down

0 comments on commit 1ac193c

Please sign in to comment.