ID EN
Typing

TypeGuard

Python 3.11

Special typing construct for marking user-defined type guard functions.

Syntax

PYTHON
typing.TypeGuard

Examples

Example 1
PYTHON
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``.
        ...
Example 2
PYTHON
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!")