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)
Unfortunately not, no. We do now consider the
raise_error()call to be terminal (you can check that by adding an unknown symbol after theraise_error()call, for which no error will be emitted, since it’s unreachable), but we do not yet preserve thex is not Nonenarrowing 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.
Also for
os.execl,os.execle,os.execlp,os.execlpe,os.execvp,os.execvpe.Funcs in
os.pythat mention “replacing the current process” in their doc.Same issue, different symptoms. I have this simplified example that’s causing
warning[possibly-unbound-attribute]: Attributeignoreon typeQCloseEvent | Noneis possibly unboundsince ty doesn’t see thatCan confirm 😃. Thank you for the analysis.
When subclassing, in your example, if you explicitly annotate
selfasFooParser, then the error vanishes, for example: https://play.ty.dev/631e5827-6f8a-4144-9261-428a127486f0.Without this annotation, the type of
selfwhich ty infers isUnknown(which is also thus the inferred type ofself.exit), which causes the error you see. Not inferring the type ofselfcorrectly 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.errorcallssys.exit:This issue persists when subclassing:
Ty emits:
Function always implicitly returnsNone, which is not assignable to return typeNeverty[invalid-return-type](https://ty.dev/rules#invalid-return-type).