Type narrowing with validation function that raises exception?

What you’re looking for is a “type assert function”. TypeScript has the ability to define such functions using the asserts <type> return type annotation. There is currently no analogous mechanism in Python’s type system. There has been some discussion of adding a TypeAssert special form to support this use case, but it hasn’t gotten to the formal specification phase.

In the meantime, you can wrap your untyped validation function with a type guard function.

def validate_data(x) -> None:
    if "val" not in x:
        raise ValueError()

def is_data_valid(x: DataRaw) -> TypeGuard[DataFull]:
    validate_data(x)
    return True
1 Like