Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.TypeGuard

Give a Boolean predicate a positive narrowing rule for its first positional argument in static analysis.

Version: Python 3.14; repository image, production runtime not attested

Syntax

def is_names(value: list[object]) -> TypeGuard[list[str]]: ...

Give a Boolean predicate a positive narrowing rule for its first positional argument in static analysis.

When the test passes, a checker treats that argument as the stated type, even for invariant containers such as list. A negative result does not establish the complementary type, and Python never validates the predicate’s promise.

The example checks each element, so the empty list also passes.

Examples

from typing import TypeGuard
def is_names(value: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in value)
def join(values: list[object]) -> str:
    return ",".join(values) if is_names(values) else "mixed"
print(repr(join([])), join(["x", "y"]), join(["x", 2]))

Result

'' x,y mixed

The example checks each element, so the empty list also passes.

Sources