@@ -933,6 +933,80 @@ These can be used as types in annotations using ``[]``, each having a unique syn
933933
934934 .. versionadded :: 3.9
935935
936+
937+ .. data :: TypeGuard
938+
939+ Special typing form used to annotate the return type of a user-defined
940+ type guard function. ``TypeGuard `` only accepts a single type argument.
941+ At runtime, functions marked this way should return a boolean.
942+
943+ ``TypeGuard `` aims to benefit *type narrowing * -- a technique used by static
944+ type checkers to determine a more precise type of an expression within a
945+ program's code flow. Usually type narrowing is done by analyzing
946+ conditional code flow and applying the narrowing to a block of code. The
947+ conditional expression here is sometimes referred to as a "type guard"::
948+
949+ def is_str(val: Union[str, float]):
950+ # "isinstance" type guard
951+ if isinstance(val, str):
952+ # Type of ``val`` is narrowed to ``str``
953+ ...
954+ else:
955+ # Else, type of ``val`` is narrowed to ``float``.
956+ ...
957+
958+ Sometimes it would be convenient to use a user-defined boolean function
959+ as a type guard. Such a function should use ``TypeGuard[...] `` as its
960+ return type to alert static type checkers to this intention.
961+
962+ Using ``-> TypeGuard `` tells the static type checker that for a given
963+ function:
964+
965+ 1. The return value is a boolean.
966+ 2. If the return value is ``True ``, the type of its argument
967+ is the type inside ``TypeGuard ``.
968+
969+ For example::
970+
971+ def is_str_list(val: List[object]) -> TypeGuard[List[str]]:
972+ '''Determines whether all objects in the list are strings'''
973+ return all(isinstance(x, str) for x in val)
974+
975+ def func1(val: List[object]):
976+ if is_str_list(val):
977+ # Type of ``val`` is narrowed to List[str]
978+ print(" ".join(val))
979+ else:
980+ # Type of ``val`` remains as List[object]
981+ print("Not a list of strings!")
982+
983+ If ``is_str_list `` is a class or instance method, then the type in
984+ ``TypeGuard `` maps to the type of the second parameter after ``cls `` or
985+ ``self ``.
986+
987+ In short, the form ``def foo(arg: TypeA) -> TypeGuard[TypeB]: ... ``,
988+ means that if ``foo(arg) `` returns ``True ``, then ``arg `` narrows from
989+ ``TypeA `` to ``TypeB ``.
990+
991+ .. note ::
992+
993+ ``TypeB `` need not be a narrower form of ``TypeA `` -- it can even be a
994+ wider form. The main reason is to allow for things like
995+ narrowing ``List[object] `` to ``List[str] `` even though the latter
996+ is not a subtype of the former, since ``List `` is invariant.
997+ The responsibility of
998+ writing type-safe type guards is left to the user. Even if
999+ the type guard function passes type checks, it may still fail at runtime.
1000+ The type guard function may perform erroneous checks and return wrong
1001+ booleans. Consequently, the type it promises in ``TypeGuard[TypeB] `` may
1002+ not hold.
1003+
1004+ ``TypeGuard `` also works with type variables. For more information, see
1005+ :pep: `647 ` (User-Defined Type Guards).
1006+
1007+ .. versionadded :: 3.10
1008+
1009+
9361010Building generic types
9371011""""""""""""""""""""""
9381012
0 commit comments