Repository navigation
Treat an imported Final as a static condition in reachability analysis - #12016
Trim21 (trim21) wants to merge 2 commits into
Conversation
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
|
this is also related to #12002 , would you mind also review that? Bill Schnurr (@bschnurr) |
|
Reviewed |
Yeah the |
|
and also |
🔴 Pyright CLI QA —
|
|
I think the underlying problem is in the shared narrowing/truthiness logic that reachability analysis relies on, not in this PR's alias handling. This PR only makes the cross-module case hit it. The same problem already exists for same-module references on My preference is to merge these two PRs (#12002 and this one) first (or one of them), and then fix the shared logic in the other PR, so same-module and cross-module references end up with the same behavior. Until that fix lands, this case remains a known false negative. |
|
If we want to keep the change contained to this PR, we could limit the scope to literal-typed Finals (e.g. |
|
And personally I don't think anyone write code like this in real world... |
|
I saw this PR cross-referenced on #12057 but couldn't find where in this thread, so I'm clarifying here. I opened #12057 to replace #12002, this PR and #12040 with one change. Your diagnosis in #12002 is right: the reachability check evaluates a condition's type only when the referenced symbol is typed ( #12057 decides reachability from the reference's type, whether it's a local name, an imported name or |
Peronslly I'm ok to fix this in one or multiple PR, I split it to make reviewer to review each one easier, I just want to fix this ASAP, so I'm also OK if maintainers decide to merge #12057 as long as we are fixing same thing |
Yes, we are fixing the same thing. I ran the test samples from #12002, #12016 and #12040, each at its current head, on #12057's head 7a48423 with |
Mangesh Raut (mangeshraut712)
left a comment
There was a problem hiding this comment.
Verified with a minimal multi-module probe: direct, as-renamed, comparison, and repeated imports all prune correctly on the PR and none prune on main. The three must-still-analyze controls behave as intended.
✅ Import-shape probe — 4 for 4 pruned on PR, 0 for 4 on main
With a flags module declaring IS_LINUX: Final = True, IS_WIN: Final = False, N: Final = 10:
| Shape | main |
PR head |
|---|---|---|
from flags import IS_WIN → if IS_WIN: |
error (branch analyzed) | pruned |
from flags import IS_LINUX as LINUX → if not LINUX: |
error | pruned |
from flags import N as NUM → if NUM != 10: |
error | pruned |
Second from flags import IS_LINUX of the same name |
error | pruned |
The as-rename cases confirm resolveAliasDeclaration(decl, /* resolveLocalNames */ true) is doing what the comment says. StaticExpression5 + the new StaticExpression6 pass on the PR head (StaticExpression6 doesn't exist on main).
✅ The controls in staticExpression6.py are the right ones
The sample checks DYNAMIC (non-static Final), ANNOTATED (Final with a declared type — not a bare literal), and PLAIN (non-Final), asserting each still requires both branches. I reproduced that independently: TYPED: Final[bool] = True stays un-pruned on the PR. That's the over-pruning guard, and it holds — the gate is resolved.isFinal && resolved.inferredTypeSource, so an explicitly annotated Final is excluded by construction.
✅ Scope is correctly limited
The description is explicit that import flags + flags.IS_WINDOWS is untouched because member access produces no flow-node reference, so this gate is never consulted. Confirmed on the PR: attribute-form access is unaffected. That's a clean, honest scope boundary rather than a half-fix.
📝 One thing to double-check before merge
isImportedFinalWithInitializer iterates symbol.getDeclarations() and calls resolveAliasDeclaration per alias. For a name imported many times (common with wildcard + explicit), this runs on each reference in a condition. The comment says the fast path for declared types is unaffected (hasTypedDeclarations() short-circuits first), which is correct — but a name that is only alias-declared will pay the resolve cost at every if site. Probably negligible; worth a glance at a file with hundreds of such conditions if one exists in the perf corpus.
Summary
The reachability analysis now treats a bare
Finaldeclared in the same module as a static condition, but that does not help the way such a constant is usually shared — declared once in a config module and imported everywhere else:reveal_type(IS_WINDOWS)inmain.pyis alreadyLiteral[False]; only the reachability analysis disagrees. An imported name is represented by an alias declaration, which has no declared type in the file that reads it, so the existing gate skips the reference.The typing specification covers this case by name: "If a module declares a Final variable and another module imports that variable in an import statement by name or wildcard, the imported symbol inherits the Final type qualifier." (Type qualifiers — Importing
FinalVariables). The imported symbol therefore inherits the qualifier, and the rule for a bareFinalinitialized with a literal applies at the point of use, soif IS_WINDOWS:is to be treated asif False:. Pyright honors the inherited qualifier for assignment checking but not for reachability, even though it already produces the correctLiteral[False]type for the imported name.The same clause applies to by-name and wildcard imports only —
import flagsdoes not import the variable, so attribute access is outside its scope and is not changed here.isImportedFinalWithInitializerfollows an alias declaration to the symbol it refers to (includingasrenames) and reports whether that symbol is aFinalwith an initializer. The reference is then narrowed exactly like a locally declaredFinal, and the branch is pruned only when narrowing yieldsNever.Part of #11980. Member access is untouched for a second, mechanical reason:
flags.IS_WINDOWSproduces no flow-node reference at all, so the gate this change extends is never consulted for it.Evidence and validation
Baseline and head revisions: baseline
c2b4c6d7110d100cfdde2514955289f2780a43de(upstreammain), heada411db4f447b95b1ed5f54a9f1121c5d9164fa9d.Commands and configuration:
Both workloads were analyzed with
--pythonplatform Linux. New samples:staticExpression6.py(imports fromstaticExpression5.py), analyzed withpythonVersion 3.11andpythonPlatform Linux.Tests and checks run: full jest suite; the new
StaticExpression6test;tsc --noEmit;prettier --check;eslint.Observed results:
reportAssignmentTypediagnostics on the baseline and three with the change. The three removed are the assignments in branches that cannot execute on Linux:x = "error!"in the body ofif IS_WINDOWS:, in theelseofif not IS_WINDOWS:, and in theelseofif VERSION_AT_LEAST_3_9:. The three that remain are the intended controls: an importedFinalwhose initializer is not statically evaluable, an importedFinal[bool](whose type staysbool), and an imported value that is notFinal.from flags import IS_WINDOWS as WIN,from flags import *followed byif IS_WINDOWS:,if not IS_WINDOWS:,if IS_WINDOWS and X:, andwhile IS_WINDOWS:all prune with the change and report on the baseline. Two modules that import aFinalfrom each other prune correctly without recursion.pyright-internal/src: unchanged (diffof the two sorted diagnostic lists is empty).node packages/pyright/dist/pyright.jsonpackages/pyright-internal/srcwas used for the diagnostics comparison above.Limitations or unrun checks: the incremental and watch paths were exercised only through the existing language-server test suites. The alias-resolution path is reached once per conditional reference without a declared type; no pathological input was constructed to measure that path in isolation.
Type precision and performance
No type-precision change: the imported reference keeps the type it already had (
Literal[False]for a bareFinal), and narrowing producesNeveronly where it already did for annotatedFinaland inline static conditions. An importedFinal[bool]keepsbooland is therefore still not pruned.Measured with two runs per build, taking the minimum: typeshed's stdlib 3.92s → 4.05s,
pyright-internal/src9.48s → 9.17s. The added work is a scan of the symbol's declarations and oneresolveAliasDeclarationcall, and only for references that have no declared type — that is, imported names — so the fast path for declared types is untouched.