Skip to content

Treat an imported Final as a static condition in reachability analysis - #12016

Open
Trim21 (trim21) wants to merge 2 commits into
microsoft:mainfrom
trim21:final-imported-condition
Open

Trim21 (trim21) wants to merge 2 commits into
microsoft:mainfrom
trim21:final-imported-condition

Conversation

@trim21

@trim21 Trim21 (trim21) commented Nov 15, 2026 •

Copy link
Copy Markdown

Summary

The reachability analysis now treats a bare Final declared 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:

# flags.py
import sys
from typing import Final

IS_WINDOWS: Final = sys.platform == "win32"

# main.py
from flags import IS_WINDOWS

if IS_WINDOWS:
    os.startfile(path)      # reportAttributeAccessIssue when targeting Linux

reveal_type(IS_WINDOWS) in main.py is already Literal[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 Final Variables). The imported symbol therefore inherits the qualifier, and the rule for a bare Final initialized with a literal applies at the point of use, so if IS_WINDOWS: is to be treated as if False:. Pyright honors the inherited qualifier for assignment checking but not for reachability, even though it already produces the correct Literal[False] type for the imported name.

The same clause applies to by-name and wildcard imports only — import flags does not import the variable, so attribute access is outside its scope and is not changed here.

isImportedFinalWithInitializer follows an alias declaration to the symbol it refers to (including as renames) and reports whether that symbol is a Final with an initializer. The reference is then narrowed exactly like a locally declared Final, and the branch is pruned only when narrowing yields Never.

Part of #11980. Member access is untouched for a second, mechanical reason: flags.IS_WINDOWS produces no flow-node reference at all, so the gate this change extends is never consulted for it.

Evidence and validation

  • Added or updated focused regression coverage for the motivating behavior.
  • Checked a nearby invalid case that must remain rejected and an unaffected neighboring control.
  • Compared focused diagnostics and revealed types against the pre-change baseline where feasible.
  • Reviewed the complete patch for architectural fit, type-precision changes, and performance impact.
  • Ran the relevant tests and checks listed below.

Baseline and head revisions: baseline c2b4c6d7110d100cfdde2514955289f2780a43de (upstream main), head a411db4f447b95b1ed5f54a9f1121c5d9164fa9d.

Commands and configuration:

cd packages/pyright-internal && npx jest
cd packages/pyright-internal && npx jest typeEvaluator8.test.ts -t StaticExpression6
npx tsc --noEmit -p packages/pyright-internal
node packages/pyright/dist/pyright.js --pythonplatform Linux --typeshedpath <typeshed>/typeshed-fallback <target>

Both workloads were analyzed with --pythonplatform Linux. New samples: staticExpression6.py (imports from staticExpression5.py), analyzed with pythonVersion 3.11 and pythonPlatform Linux.

Tests and checks run: full jest suite; the new StaticExpression6 test; tsc --noEmit; prettier --check; eslint.

Observed results:

  • The new sample reports six reportAssignmentType diagnostics 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 of if IS_WINDOWS:, in the else of if not IS_WINDOWS:, and in the else of if VERSION_AT_LEAST_3_9:. The three that remain are the intended controls: an imported Final whose initializer is not statically evaluable, an imported Final[bool] (whose type stays bool), and an imported value that is not Final.
  • Variants verified manually against the same baseline: from flags import IS_WINDOWS as WIN, from flags import * followed by if IS_WINDOWS:, if not IS_WINDOWS:, if IS_WINDOWS and X:, and while IS_WINDOWS: all prune with the change and report on the baseline. Two modules that import a Final from each other prune correctly without recursion.
  • Full suite: 3730 passed, 20 skipped.
  • Diagnostics on typeshed's stdlib: unchanged (557 errors, 66 warnings). Diagnostics on pyright-internal/src: unchanged (diff of the two sorted diagnostic lists is empty).
  • node packages/pyright/dist/pyright.js on packages/pyright-internal/src was 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 bare Final), and narrowing produces Never only where it already did for annotated Final and inline static conditions. An imported Final[bool] keeps bool and is therefore still not pruned.

Measured with two runs per build, taking the minimum: typeshed's stdlib 3.92s → 4.05s, pyright-internal/src 9.48s → 9.17s. The added work is a scan of the symbol's declarations and one resolveAliasDeclaration call, and only for references that have no declared type — that is, imported names — so the fast path for declared types is untouched.

@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@trim21

Trim21 (trim21) commented Nov 17, 2026 •

Copy link
Copy Markdown
Author

this is also related to #12002 , would you mind also review that? Bill Schnurr (@bschnurr)

@bschnurr

Copy link
Copy Markdown
Member

Reviewed 2d548cca integrated with d95fe63b. All four focused StaticExpression tests passed. Compared with main, the PR removes false reportReturnType diagnostics for from flags import OFF as IMPORTED_OFF and the negation of a direct ON import, while a dynamic imported flag and a shadowing bool parameter still produce their reachable-branch errors. if flags.OFF and a conditional expression with the imported name still report the same false positives as main; these are outside the demonstrated direct-import statement fix. This PR and #12002 each integrate cleanly with current main, but combining their heads conflicts in codeFlowEngine.ts; the combined version needs both the alias and local-declaration cases.

@trim21

Trim21 (trim21) commented Nov 18, 2026 •

Copy link
Copy Markdown
Author

Reviewed 2d548cca integrated with d95fe63b. All four focused StaticExpression tests passed. Compared with main, the PR removes false reportReturnType diagnostics for from flags import OFF as IMPORTED_OFF and the negation of a direct ON import, while a dynamic imported flag and a shadowing bool parameter still produce their reachable-branch errors. if flags.OFF and a conditional expression with the imported name still report the same false positives as main; these are outside the demonstrated direct-import statement fix.

Yeah the module.var is a separate case I'll fix later and not part of this pr

@trim21

Copy link
Copy Markdown
Author

and also from mod import FLAG is a more common case then mod.FLAG and it need only small change to fix, so it's a seprated PR, we can resolve this more quickly.

@heejaechang

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — 2d548cca — verdict: red

Automated CLI checks compared this change with its base revision.
19 focused check(s) completed.

Needs review: reportAssignmentType no longer reported

The base reports reportAssignmentType for this example; the PR does not. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

main.py

reveal_type(0)
from values import FLAG
if not FLAG:
    value: int = "reachable"

pyrightconfig.json

{
  "include": [
    "main.py"
  ],
  "pythonVersion": "3.11",
  "typeCheckingMode": "basic",
  "reportUnreachable": false
}

values.py

from typing import Final
class Meta(type):
    def __bool__(cls) -> bool:
        return False
class Falsy(metaclass=Meta):
    pass
FLAG: Final = Falsy

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base 0be51defd3c0c2e7fe2e4cd91492511823397174

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportAssignmentType",
      "message": "Type \"Literal['reachable']\" is not assignable to declared type \"int\"\n  \"Literal['reachable']\" is not assignable to \"int\"",
      "range": {
        "start": [
          3,
          17
        ],
        "end": [
          3,
          28
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 2d548cca4e9ae5d79d3e9772dffc83c7228eabfd

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

@trim21

Copy link
Copy Markdown
Author

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 main (FLAG: Final[type[Falsy]] = Falsy with a metaclass __bool__ is pruned), so an imported-Final-specific condition here would make the two paths use different rules.

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.

@trim21

Copy link
Copy Markdown
Author

If we want to keep the change contained to this PR, we could limit the scope to literal-typed Finals (e.g. Final = False and platform/version checks), so Final = Falsy stays reachable. Would you like me to make that change?

@trim21

Copy link
Copy Markdown
Author

And personally I don't think anyone write code like this in real world...

@crypt0lith

Copy link
Copy Markdown
Contributor

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 (hasTypedDeclarations()), and a bare Final is just a qualifier. But each of the three PRs widens that same check for one more way of reaching a Final: local, imported, then through a module. #12002 and this PR both rewrite it from main, so they conflict.

#12057 decides reachability from the reference's type, whether it's a local name, an imported name or module.NAME, as ty does (reachability.rs:2028-2034). That makes the type's truthiness decide the branch, so it also evaluates a class object's truthiness through its metaclass __bool__, and a tuple subclass's through its own __bool__. That's the shared logic from #12016 (comment), and it means neither the merge order nor limiting the scope to literal-typed Finals is needed.

@trim21

Copy link
Copy Markdown
Author

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 (hasTypedDeclarations()), and a bare Final is just a qualifier. But each of the three PRs widens that same check for one more way of reaching a Final: local, imported, then through a module. #12002 and this PR both rewrite it from main, so they conflict.

#12057 decides reachability from the reference's type, whether it's a local name, an imported name or module.NAME, as ty does (reachability.rs:2028-2034). That makes the type's truthiness decide the branch, so it also evaluates a class object's truthiness through its metaclass __bool__, and a tuple subclass's through its own __bool__. That's the shared logic from #12016 (comment), and it means neither the merge order nor limiting the scope to literal-typed Finals is needed.

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

@crypt0lith

Copy link
Copy Markdown
Contributor

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 --pythonplatform Linux --pythonversion 3.11. The results matched what your PRs expected for all of them.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants