@@ -846,22 +846,25 @@ def TypeGuard(self, parameters):
846
846
2. If the return value is ``True``, the type of its argument
847
847
is the type inside ``TypeGuard``.
848
848
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)
850
854
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!")
859
862
860
863
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
861
864
form of ``TypeA`` (it can even be a wider form) and this may lead to
862
865
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
865
868
writing type-safe type guards is left to the user.
866
869
867
870
``TypeGuard`` also works with type variables. For more information, see
0 commit comments