On Sat, 13 Feb 2021 19:48:10 -0000 "Eric Traut" email@example.com wrote:
...to work around deficiencies in the current generation of Python typecheckers
It sounds like you're implying that this functionality will be no longer needed at some point in the future when type checkers improve in some (unspecified) manner. If that's what you meant to convey, then I disagree. I think there will be an ongoing need for this functionality. There's good evidence for this in TypeScript, where user-defined type guards have been adopted widely by developers.
That's certainly a good argument on its own (providing cross-language functionality and adopting known best practices).
But taken without context like that, I wonder if the example from the PEP647:
def is_str_list(val: List[object]) -> bool: """Determines whether all objects in the list are strings""" return all(isinstance(x, str) for x in val)
def func1(val: List[object]): if is_str_list(val): print(" ".join(val)) # Error: invalid type
would work if "type guard function" was inlined:
def func1(val: List[object]): if all(isinstance(x, str) for x in val): print(" ".join(val)) # Is this valid or not?
If the answer is "no", then it points to pretty weak ability of abstract interpretation of the current typecheckers. If the answer is "yes", it's more reassuring, but then the problem is weak interprocedural capabilities of the current typecheckers.
I certainly understand all the technical challenges with that (likely performance), asymptotically turning into halting problem. And yet I may imagine that many practically useful typeguards will be simple enough (like above), and may be automatically type-inferred in the future.
Then the syntax for explicit type guard annotation is less important (would be used as an exception, not a rule), and if it's useful now to keep up the pace of the typechecker research, then I'd be +1 with it (instead of nitpicking at it, as seem to be the case with other recent replies).
-- Eric Traut Contributor to Pyright & Pylance Microsoft Corp.