ty: calls to functions returning `Never`/`NoReturn` are terminal

Summary

The following code emits a invalid-return-type diagnostic, but shouldn’t:

from typing import NoReturn
import sys

def f() -> NoReturn:
#          ^^^^^^^^ Function can implicitly return `None`, which is not assignable to return type `Never`
    sys.exit(1)

sys.exit is annotated with returning NoReturn, but the problem is that we don’t have an explicit return statement here.

This is related to unreachable code analysis. We already have some special handling for detecting whether or not the end of scope is reachable (i.e. replacing sys.exit(1) with while True: pass works fine), but this does not take calls to functions returning Never/NoReturn into account.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 10
  • Comments: 17 (4 by maintainers)

Commits related to this issue

Most upvoted comments

My previous test case isnt supported correctly still. #180 (comment)

Unfortunately not, no. We do now consider the raise_error() call to be terminal (you can check that by adding an unknown symbol after the raise_error() call, for which no error will be emitted, since it’s unreachable), but we do not yet preserve the x is not None narrowing constraint from the (implicit) else branch in that conditional. This is already tracked in https://github.com/astral-sh/ty/issues/690.

Currently NoReturn cannot be used to narrow a type. Which is a relatively common pattern in for example Flask examples. Where abort() can be used to return an error code early. This can be used to make sure that the request contains valid data.

For reference here is another example that currently doesnt work.

from typing import NoReturn, reveal_type

def raise_error() -> NoReturn:
    raise Exception('test')


def test(x: str | None) -> None:
    if x is None:
        raise_error()
    
    reveal_type(x)
    # Should be "str" is "str | None"

Also for os.execl, os.execle, os.execlp, os.execlpe, os.execvp, os.execvpe.

Funcs in os.py that mention “replacing the current process” in their doc.

def restartLow() -> typing.NoReturn:
	"""Will not return from the function."""
	os.execl(
		sys.executable,
		sys.executable,
		*sys.argv,
	)
def execl(file, *args):
    """execl(file, *args)

    Execute the executable file with argument list args, replacing the
    current process. """
    execv(file, args)

Same issue, different symptoms. I have this simplified example that’s causing warning[possibly-unbound-attribute]: Attribute ignoreon typeQCloseEvent | None is possibly unbound since ty doesn’t see that

from PySide6 import QtGui
from PySide6.QtWidgets import QMainWindow

class MainWindow(QMainWindow):
    def closeEvent(self, event: QtGui.QCloseEvent | None = None):
        """Exit safely when closing the window."""

        if event is None or False:  # `or False` is actually some other condition, simplified for this example
            sys.exit(1)  # Here ty should see that `event` can't be `None` if this branch wasn't taken

        # ... some more checks and user prompts happened here

        # Fallthrough case: Prevent program from closing.
        event.ignore()

though @sharkdp could confirm.

Can confirm 😃. Thank you for the analysis.

My issue still persists even after the pull request. Should I open a new issue?

When subclassing, in your example, if you explicitly annotate self as FooParser, then the error vanishes, for example: https://play.ty.dev/631e5827-6f8a-4144-9261-428a127486f0.

Without this annotation, the type of self which ty infers is Unknown (which is also thus the inferred type of self.exit), which causes the error you see. Not inferring the type of self correctly seems to be tracked at https://github.com/astral-sh/ty/issues/159, though @sharkdp could confirm.

Most of the false positives were fixed in https://github.com/astral-sh/ruff/pull/18333, but see also https://github.com/astral-sh/ty/issues/685 for an issue pertaining to type narrowing.

This error arises in the context of the argparse module, where argparse.ArgumentParser.error calls sys.exit:

    def exit(self, status=0, message=None):
        if message:
            self._print_message(message, _sys.stderr)
        _sys.exit(status)

    def error(self, message):
        """error(message: string)

        Prints a usage message incorporating the message to stderr and
        exits.

        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        """
        self.print_usage(_sys.stderr)
        args = {'prog': self.prog, 'message': message}
        self.exit(2, _('%(prog)s: error: %(message)s\n') % args)

This issue persists when subclassing:

class FooParser(argparse.ArgumentParser):

    def error(self, message: str) -> NoReturn:
        self.exit(1, f"{self.usage}: error: {message}\n")

Ty emits: Function always implicitly returns None, which is not assignable to return type Neverty[invalid-return-type](https://ty.dev/rules#invalid-return-type).