Skip to content

Generate a warning/error on assigning values of type NoReturn #4179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Wilfred opened this issue Oct 30, 2017 · 6 comments
Open

Generate a warning/error on assigning values of type NoReturn #4179

Wilfred opened this issue Oct 30, 2017 · 6 comments

Comments

@Wilfred
Copy link

Wilfred commented Oct 30, 2017

import sys
from typing import List
from mypy_extensions import NoReturn

def never_returns() -> NoReturn:
    sys.exit(1)

def foo() -> None:
    x = never_returns()

It would be nice if mypy warned in this situation.

@ilevkivskyi
Copy link
Member

This example actually generates an error on master:

__tmp__.py:9: error: Need type annotation for variable

For me this is OK. We can keep this open if you want a dedicated error message for such cases, but I think this is quite low priority.

@sobolevn
Copy link
Member

sobolevn commented Feb 3, 2019

Here's another example of how NoReturn behaves incorrectly:

from typing import NoReturn, Union


def one() -> NoReturn:
    raise ValueError()

def two() -> int:
    return 1

def three(arg: int) -> Union[int, NoReturn]:
    if arg > 0:
        return two()
    return one()

reveal_type(three(1))  # types.py:15: error: Revealed type is 'Union[builtins.int, <nothing>]'
reveal_type(three(1) + 1)  # types.py:16: error: Revealed type is 'builtins.int'

But, it surely should not do this.

@ilevkivskyi
Copy link
Member

But, it surely should not do this.

Why is this incorrect? I don't see any problem with simplifying NoReturn out of the union, it is a subtype of all types. In Python almost every function can raise an exception, so there is no point in annotating anything as -> Union[int, NoReturn], it is just -> int.

@Dambre
Copy link

Dambre commented Feb 20, 2020

@ilevkivskyi Year later lol. What if the exception is raised explicitly? In my opinion it would make sense to note that this is expected behaviour, isn't it?

def somefunc(sth: int) -> Union[bool, NoReturn]:
    if sth:
        return True
    raise Exception

@ikeyan
Copy link

ikeyan commented Sep 3, 2020

@Dambre
Then you are going to annotate almost every function with Union[..., NoReturn].
Read this: #4116 (comment)

@A5rocks
Copy link
Collaborator

A5rocks commented Mar 7, 2025

Surely --warn-unreachable works well enough for this, right? If you have any functionality after the assignment, then it will warn. Better yet it even works transitively! str(never_returns()) will still warn!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants