Skip to content

Narrow bare Final for reachability, give static conditions literal types - #12057

Open
crypt0lith wants to merge 3 commits into
microsoft:mainfrom
crypt0lith:fix/reachability-final-ref
Open

crypt0lith wants to merge 3 commits into
microsoft:mainfrom
crypt0lith:fix/reachability-final-ref

Conversation

@crypt0lith

@crypt0lith crypt0lith commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #11980
Supersedes #12002, #12016, #12040

Pyright handles static conditions inconsistently depending on the context.

  1. A static condition marks a branch as unreachable only when the expression is inlined, or when it is declared Final[...]. A bare Final declaration is skipped, even though the assigned value's inferred type is Literal[False]/Literal[True]. Declared Final[...] static conditions are also skipped during reachability checks when the name is imported.
  2. An inlined static condition is inferred as bool instead of Literal[False]/Literal[True].
  3. A declared static condition is ignored for several bool-typed parameters of special constructs (namedtuple's rename, dataclass and dataclass_transform), as well as for ternary tests.
ty 0.0.107 and pyright 1.1.414, --pythonplatform Linux
import os
import sys
from collections import namedtuple
from dataclasses import dataclass, field
from typing import Final

IS_WIN: Final = sys.platform == "win32"
RENAME: Final = True
FROZEN: Final = True
NO_INIT: Final = False

reveal_type(sys.platform == "win32")      # ty: Literal[False]   pyright: bool
reveal_type(not sys.platform == "win32")  # ty: Literal[True]    pyright: bool

if IS_WIN:
    os.startfile("x")                     # ty: no error         pyright: error

reveal_type(1 if IS_WIN else "")          # ty: Literal[""]      pyright: Literal[1, '']
reveal_type(1 if RENAME else "")          # ty: Literal[1]       pyright: Literal[1, '']
reveal_type(1 if print else "")           # ty: Literal[1]       pyright: Literal[1, '']
reveal_type(1 if None else "")            # ty: Literal[""]      pyright: Literal[1, '']

NT = namedtuple("NT", ["abc", "def"], rename=RENAME)
reveal_type(NT._fields)  # ty: tuple[Literal["abc"], Literal["_1"]]   pyright: error, tuple[str, ...]

@dataclass(frozen=FROZEN)
class DC:
    a: int
    b: str = field(init=NO_INIT, default="")

DC(1).a = 2  # ty: error   pyright: no error
DC(1, "")    # ty: error   pyright: no error

How ty handles some of these cases:

Root cause

  1. The reachability check on a condition's reference handles only a name, and only when the name has a declared type. A bare Final has none: Final is a qualifier, so its type is inferred from the assigned value. An imported name has none either, since its declaration is the import, and module.NAME isn't a name. When the check does find the branch unreachable, a Final with a literal type is reported by reportUnreachable, unlike the inline static condition.
  2. A static condition gets a literal type only as the right-hand side of an assignment. In any other expression it's bool.
  3. namedtuple rename, the dataclass and dataclass_transform parameters and the ternary test are evaluated with evaluateStaticBoolExpression, which only reads syntax. An argument of type Literal[True] or Literal[False] is ignored by namedtuple and dataclass, dataclass_transform reports it as not statically evaluated, and the ternary evaluates to both branches.

Fix

  1. Decide reachability from the type of a bare Final, an imported name and a module member access (module.NAME), as for a local name with a declared type. When a Final with a literal type makes a branch unreachable, treat the branch like one under an inline static condition, which reportUnreachable doesn't report.
  2. Give a static condition a literal type when it is a name, member access, or a binary or unary op of type bool. Replaces the assignment-only conversion.
  3. Evaluate these from the argument's type: rename when it's always truthy, the dataclass parameters when it's a constant bool, and the ternary's branch when the test is constant. TypedDict total and closed stay syntactic, since the spec allows only literal True or False there.

Test

Cases added to staticExpression4.py
Case Expected Description
func1 local Final platform check, branch pruned
func2 imported Final platform check, branch pruned
func3 not of an imported Final platform check, branch pruned
func4 Final platform check imported with as, branch pruned
func5 imported Final[Literal[False]], branch pruned
func6 module.NAME Final platform check, branch pruned
func7 error Final whose value isn't static, branch reachable
func8 error platform check not declared Final, branch reachable
func9 error Final class attribute read through an instance, branch reachable
func10 error Any parameter named like the module, branch reachable
func11 error isinstance on a Final with a non-literal type, branch reachable
func12 module.NAME read before the module name is rebound, branch pruned
func13 error module.NAME read after the module name is rebound to an instance, branch reachable
Cases added to staticExpression5.py
Case Expected Description
func1 platform, version, os.name, TYPE_CHECKING and not checks are literal
func2 or with a true static condition is Literal[True]
func3 defined constant name keeps its literal type
func4 error false static condition assigned to Literal[True]
Cases added to ternary1.py
Case Expected Description
func1 always-truthy test, true branch's type
func2 always-falsy test, false branch's type
func3 bool test, both branches' types
Cases added to namedTuple9.py
Case Expected Description
NT6 rename from a Final true, keyword field renamed
NT7 error rename from a Final false, keyword field
Cases added to dataclass6.py
Case Expected Description
ClassC error field(init=) from a Final false, field passed to __init__
Cases added to dataclassKwOnly1.py
Case Expected Description
DC7 error field(kw_only=) from a Final true, field passed positionally
Cases added to dataclassFrozen1.py
Case Expected Description
DC7 error frozen= from a Final true, field assigned
Cases added to dataclassTransform1.py
Case Expected Description
Customer4 error frozen_default= from a Final true, field assigned
create_model_frozen3 error frozen_default= whose value isn't static

In typeNarrowing1.py, maybe is now a non-literal bool, since it was never reassigned and its ternaries now select one branch. In tupleLiteralInference5.py, the ternary in conditional_control now has only the selected branch's literal, so appending ("",) is an error.

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: 2981f9f and e7312d1.

Commands and configuration:

  • mypy_primer --type-checker pyright --output concise --old 23aa785c7 --new c9f05ea71, on projects that use sys.platform, sys.version_info, os.name or TYPE_CHECKING outside a plain if or elif test.
  • Benchmarks, dev CLI builds of 2981f9f and c9f05ea run interleaved: pip's src with its venv, 5 rounds per build; staticExpression3.py, staticExpression4.py and staticExpression5.py with --pythonplatform Linux, 30 runs per build.

Tests and checks run: jest on the tests for every changed sample and the other static condition, namedtuple and TypedDict tests; prettier, eslint and tsc.

Observed results:

  • mypy_primer: no diagnostic differences on mypy, pip, spack, pwndbg, vision, ignite and django-modern-rest.
  • pip: 29.73 s on the base and 29.85 s on the head (means; spreads 1.22 s and 0.92 s), with 597 errors and 34 warnings on both.
  • The three samples: 1.770 s on the base and 1.766 s on the head (means; SD 0.045 s and 0.051 s).

Limitations or unrun checks: Candidates with matches that weren't run, for disk space: bokeh, dd-trace-py, ibis, prefect, rotki, streamlit and zulip.

🤖 AI-assisted validation

Type precision and performance

No type widens. Static conditions are Literal[True] or Literal[False] in any expression, and a ternary whose test is constant has only that branch's type.

Author responsibility

Read the AI contribution policy and confirm before submitting:

  • I personally reviewed and understand this entire pull request, including any AI-assisted work, ran the checks appropriate to the change, and take responsibility for the contribution and its follow-up.

Reachability narrows a condition's reference only when its symbol
has typed declarations, which excludes a bare Final, and never for
a module member access. Accept a Final assigned a value in its
declaration, imported or as 'module.NAME', and classify a branch
pruned by a Final with a literal type as a static condition.

Fixes microsoft#11980
A statically evaluated condition received a literal type only as the
right side of an assignment, so 'sys.platform == "win32"' was bool
as an argument or an operand. Assign the literal type wherever a
bool-typed name, member access, unary or binary operation evaluates
statically, and remove the assignment special case.

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.

Treat Final constants initialized from static platform/version checks as static conditions

1 participant