Typing and Generics

typing.TypeGuard

Annotates a boolean predicate that narrows the first applicable argument to T on a true result. Unlike TypeIs, T need not be a subtype of the input type; false results do not narrow. The predicate must be sound.

Formal Syntax & Structure

python syntaxpython
typing.TypeGuard[T]

Return Value

type expression

Typing construct or runtime result as described; static typing rules are not runtime validation.

Working Example

Example Snippetpython
from typing import TypeGuard
def strings(values: list[object]) -> TypeGuard[list[str]]: return all(isinstance(v,str) for v in values)print((strings(['a','b']), strings([1])))
Python Reference