During the last typing meetup @erictraut mentioned that for time to time people look for ways to mark a specific overload as invalid. It often leads to developers using NoReturn
/ Never
for it which is incorrect. See also the great video by anthony on that topic: https://www.youtube.com/watch?v=WuXRn3euN8k
Example: How to annotate func
so it doesn’t accept normal strings as input and only sequences?
def func(arg: Sequence[str]) -> int: ...
func(["Hello", "World"]) # ok
func("abc") # should be an error
After thinking about it, I believe this might be fairly simple to archive if we’re to add a new SpecialForm which could be used as return type annotation for these cases, say NoMatch
. Since the overload matching happens based on the arguments, it wouldn’t need to change. Type checkers just need to check afterwards if the matched return type is NoMatch
and emit an error accordingly. The overloads for the case above would then look like this
@overload
def func(arg: str) -> NoMatch: ...
@overload
def func(arg: Sequence[str]) -> int: ...
An obvious advantage would be that this closely mirrors what people expect would work with NoReturn
.
Open questions
- Is this something worth adding support for?
- Is the return type annotation the best option? In passing, Eric mentioned maybe adding an
@add_error
decorator. - If return type annotation, is
NoMatch
the best name?
Prototype
I prototyped the implementation in mypy. For tests, it can be imported from from typing_extensions import NoMatch
.