I don't think a new syntax is needed for this. Type checkers can already support a pattern like:

def is_string_list(x: List[str]) -> Literal[True]: ...
def is_string_list(x: List[object]) -> bool: ...

It is of course more verbose, but I don't think saving two lines of code is worth adding yet another special form.
Also this can be generalized to type asserts:

def assert_is_string_list(x: List[str]) -> None: ...
def assert_is_string_list(x: List[object]) -> NoReturn: ...


On Thu, 1 Oct 2020 at 00:42, Eric Traut <eric@traut.com> wrote:
I don't see much overlap between user-defined type guards and `typing.cast`. `cast` is never used for conditional type narrowing, nor can it affect control flow within a program. `cast` also doesn't involve any logic at runtime; it simply returns the value that it was passed. Plus, as you've pointed out, `cast` does not enforce that the output type is a narrower type than the input type.

A user-defined type guard is a user-defined function that is called in a conditional expression within an if/else statement. It contains logic that executes at runtime, and the bool response changes the flow of control in the program. At static type checking time, a user-defined type guard allows the type checker to understand more about the implied type of an expression within the if/else code blocks.
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
Member address: levkivskyi@gmail.com