Issue
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?
Solution
Since the implementation of PEP 647 in Python 3.10, you can use typing.TypeGuard for this:
Using
-> TypeGuardtells the static type checker that for a given function:
The return value is a boolean.
If the return value is
True, the type of its argument is the type insideTypeGuard.
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.
Answered By - jonrsharpe Answer Checked By - David Marino (Python.Easybugfix Volunteer)
Post a Comment
Post a Comment