-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[ty] More fully support 'if typing.TYPE_CHECKING' #19412
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
base: main
Are you sure you want to change the base?
Conversation
|
Primer results suggest there's something necessary missing in the new version of our TYPE_CHECKING support here. |
The diff from |
it appears as though we're no longer viewing the remainder of the module as unreachable code (in which most diagnostics should be suppressed) following this |
Summary
#19372 added support for detecting whether a function is defined inside an
if TYPE_CHECKING
block, and if so, allowing it to be a "stub" function (empty body, even with non-None return type).This PR improves that support by also supporting it for
if typing.TYPE_CHECKING
as well asif TYPE_CHECKING
. In order to do so, it changes our basic approach toTYPE_CHECKING
support. Rather than inferring a type ofLiteral[True]
for all symbols namedTYPE_CHECKING
, instead we specially handleif
conditions with purely syntactic matching (on anyName
matchingTYPE_CHECKING
or any attribute expression with attributeTYPE_CHECKING
). This means we no longer recognize aliasing ofTYPE_CHECKING
(e.g.from typing import TYPE_CHECKING as TC
), and we'll recognizefoo.TYPE_CHECKING
no matter whatfoo
is. (In both cases this matches the behavior of all other existing type checkers.) Arguably it's better to not support aliasingTYPE_CHECKING
, given its unusual behavior of matching any variable namedTYPE_CHECKING
.We currently don't handle conditions like
if TYPE_CHECKING or get_bool()
(other type checkers do). If this proves to be relevant, we can add it.I think it would also be possible to remove the extra boolean flag on scopes and in SemanticIndexBuilder, and rely instead on reachability constraints (which we already track on scopes) for detecting when a scope is defined inside
if TYPE_CHECKING
. This would require adding new terminal reachability constraints forTYPE_CHECKING
and probablyNOT_TYPE_CHECKING
as well, which would behave likeALWAYS_TRUE
andALWAYS_FALSE
, but would also allow detecting that a reachability constraint is dependent onTYPE_CHECKING
. I didn't choose to do that here, but it's a possible future improvement.Another alternative to this entire PR would be to instead double down on our handling of
TYPE_CHECKING
in type inference rather than syntactically, add a newSpecialForm
for "the type ofTYPE_CHECKING
", and then we could evaluate reachability constraints under "considerTYPE_CHECKING
False" conditions in order to detect code that is only reachable due toTYPE_CHECKING
.Test Plan
mdtests