Indicate variable values from side-effects with Python type hinting

Viewed 61

With type-hinting in Python 3.9, once an isinstance call is made in an if-statement, the typing interpreter knows the variable type. For example:

if isinstance(value, int):
    value += 1  # <-- known to be an int

However if you wanted to do some sort of additional validation, then the typing interpreter can easily get confused. For example:

def is_positive_int(value:Any)->bool:
    return isinstance(value, int) and value>=0

if is_positive_int(value):
    value += 1  # <-- NOT known to be an int

Is it possible to mimic the behavior of, in this case, isinstance and instruct the type-interpreter to treat a variable as a specific type depending on the return of is_positive_int?

1 Answers

Since the implementation of PEP 647 in Python 3.10, you can use typing.TypeGuard for this:

Using -> TypeGuard tells the static type checker that for a given function:

  1. The return value is a boolean.

  2. If the return value is True, the type of its argument is the type inside TypeGuard.

In your case that would be:

def is_positive_int(value: Any) -> TypeGuard[int]:
    return isinstance(value, int) and value >= 0

This has been backported to Python 3.6-3.9 via typing_extensions.

Related