Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pycharm provide unreachable code because of NoReturn type hint

I am writing a test for a code that will raise an exception.

with pytest.raises(Exception) as exception:
    A.b()

assert str(exception.value) == "exception"

The function b will never return a thing and may raise an exception.
Once I put the return type of b() to def b() -> NoReturn: I am getting that the assertion will never be reached "This code is unreachable". Either I did not get the purpose of NoReturn or It is a bug in Pycharm, because once I debug it, the line is reachable.

An example of b is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def b(a: int) -> NoReturn:
    if a < 0:
        raise Exception('Negative numbers are not accepted)

>Solution :

"will never return a thing and may raise an exception" contradicts itself. A function can’t "never return a thing" and "may raise an exception" at the same time.

Even if a function does not explicitly use the return statement, None is implicitly returned.

You should change NoReturn in the type hint to None.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading