Special typing construct for marking user-defined type guard functions.
typing.TypeGuard
def is_str(val: 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 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 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!")