Some thoughts on Union[X, NoReturn]
#994
Replies: 2 comments 8 replies
|
I agree that @overload
def func(x: int) -> NoReturn:
...
@overload
def func(x: str) -> str:
...
def func(x: int | str) -> str | NoReturn:
...Without the ability to use So there is at least one legitimate use of a return type of the form def func() -> str | NoReturn:
...
reveal_type(func()) # pyright: str, mypy: Union[str, <nothing>]
func().lower() # pyright: no error, # mypy: NoReturn" of "Union[str, NoReturn]" has no attribute "lower" |
|
So, technically speaking all I see some benefit in allowing explicit Probably you can use some |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I stumbled upon code that looked like this recently:
The function's signature seems to say that it "sometimes returns int, and sometimes it never returns". Mypy is happy with this, but I am not.
There's a few reasons I think this is wrong:
Replacing
Union[int, NoReturn]here with justintis also perfectly valid.Mypy seems fine with this code:
I believe that every instance of
NoReturn | X | Y | ...can be written without the NoReturn, i.e.X | Y | ...Having
NoReturnin a union defeats its entire purpose.What's the use case of NoReturn? It is to avoid cases like these:
If instead of the function never returning, it returns even some times, mypy won't be able to give you this error, making the use of
int | NoReturnnot really useful.If
Union[X, NoReturn]is correct here, all your code is wrong.If the type hint for "The function sometimes doesn't return" is actually
Union[X, NoReturn], then any piece of code that raises an exception needs to be refactored.This, for example:
This function as well, doesn't return sometimes. Does that mean we should use
Union[int, NoReturn]here too? Even though here:The type of
numis guaranteed to beint? For this reason, I'd sayintas a return type is much better, andUnion[X, NoReturn]doesn't make sense.This is why I wanted to know why mypy allows people to use
Union[X, NoReturn]. I think it should not be allowed. I'd really like some discussion on this.All reactions