[3.12] gh-117521: Improve typing.TypeGuard docstring (GH-117522) (#117538)

(cherry picked from commit b32789ccb9)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
Miss Islington (bot) 2024-04-04 13:04:16 +02:00 committed by GitHub
parent 14aef56ebb
commit b5e12aa9ff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -848,20 +848,23 @@ def TypeGuard(self, parameters):
For example:: For example::
def is_str(val: Union[str, float]): def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
# "isinstance" type guard '''Determines whether all objects in the list are strings'''
if isinstance(val, str): return all(isinstance(x, str) for x in val)
# Type of ``val`` is narrowed to ``str``
... def func1(val: list[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``list[str]``.
print(" ".join(val))
else: else:
# Else, type of ``val`` is narrowed to ``float``. # 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 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 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 type-unsafe results. The main reason is to allow for things like
narrowing ``List[object]`` to ``List[str]`` even though the latter is not narrowing ``list[object]`` to ``list[str]`` even though the latter is not
a subtype of the former, since ``List`` is invariant. The responsibility of a subtype of the former, since ``list`` is invariant. The responsibility of
writing type-safe type guards is left to the user. writing type-safe type guards is left to the user.
``TypeGuard`` also works with type variables. For more information, see ``TypeGuard`` also works with type variables. For more information, see