Skip to content

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

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

crypt0lith wants to merge 5 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.
  4. A class object is treated as always truthy, even when its metaclass's __bool__ returns Literal[False].
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, Literal

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

class Meta(type):
    def __bool__(cls) -> Literal[False]:
        return False

class Falsy(metaclass=Meta): ...

reveal_type(Falsy or "")  # ty: Literal[""]        pyright: type[Falsy]
if not Falsy:
    reveal_type(Falsy)    # ty: <class 'Falsy'>    pyright: unreachable

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. evaluateStaticBoolExpression reads any name spelled TYPE_CHECKING as True, whatever it refers to.
  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.
  4. Truthiness checks treat a class object as always truthy, without its metaclass's __bool__ or __len__.

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. A name spelled TYPE_CHECKING counts only when it refers to typing's TYPE_CHECKING or to a variable assigned False, as in ty.
  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.
    • Only the truthiness of rename needs to be considered, not whether it's a bool, since an argument of another type is already reported by argument checking.
  4. Evaluate a class object's truthiness as an instance of its metaclass, in truthiness narrowing, and/or and the ternary.

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]
func5 bool parameter named TYPE_CHECKING stays bool, also under not
func6 local TYPE_CHECKING = False is 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
func4 class object whose metaclass __bool__ returns Literal[False], false branch's type
func5 Enum class object, true branch's type
func6 class object whose class defines __bool__ and __len__, true branch's type
func7 instance whose __bool__ returns Literal[True] and that defines __len__, true branch's type
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 6843464.

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

Static conditions are Literal[True] or Literal[False] in any expression, and a ternary whose test is constant has only that branch's type. Types widen only where main's were wrong: a bool named TYPE_CHECKING that doesn't refer to typing's, which main gave Literal[True] when assigned, and the falsy branch for a class object whose metaclass makes it possibly falsy.

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.
@heejaechang

Heejae Chang (heejaechang) commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — 68434643 — verdict: red

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

Needs review: reportReturnType no longer reported

The base reports reportReturnType 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 typing import Literal
class Falsy(tuple[int]):
    def __bool__(self) -> Literal[False]:
        return False

def bad() -> int:
    return 1 if Falsy((1,)) else 'bad' # E: reportReturnType

pyrightconfig.json

{
  "include": [
    "main.py"
  ],
  "pythonVersion": "3.13",
  "pythonPlatform": "Linux",
  "typeCheckingMode": "basic"
}

From that directory, run each built Pyright revision:

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

Base 2981f9f1ce41be5c15667da1f7a3cfda4f245089

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[1, 'bad']\" is not assignable to return type \"int\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          7,
          11
        ],
        "end": [
          7,
          38
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 68434643162acbe8b67da3eb5c62695d4168ea2c

{
  "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.

Additional reproduction: Diagnostics changed for this example

The base and PR report different diagnostics for the same example. Is this change intended?

Create these files in an empty directory:

invalid.py

reveal_type(0)
from typing import Literal, NamedTuple
class Falsy(tuple[int]):
    def __bool__(self) -> Literal[False]:
        return False
class Record(NamedTuple):
    x: int
    def __bool__(self) -> Literal[False]:
        return False

def factory() -> Falsy:
    return Falsy((1,))

def from_factory() -> int:
    return 1 if factory() else 'bad' # E: reportReturnType

def named_record() -> int:
    return 1 if Record(1) else 'bad' # E: reportReturnType

def nested() -> int:
    return (1 if Falsy((1,)) else 'bad') if True else 2 # E: reportReturnType

def negated() -> int:
    return 'bad' if not Falsy((1,)) else 1 # E: reportReturnType

parameter-control.py

reveal_type(0)
from invalid import Falsy

def parameter(value: Falsy) -> int:
    return 1 if value else 'bad'

pyrightconfig.json

{
  "include": [
    "invalid.py",
    "valid.py",
    "parameter-control.py"
  ],
  "pythonVersion": "3.13",
  "pythonPlatform": "Linux",
  "typeCheckingMode": "basic"
}

valid.py

reveal_type(0)
from typing import Literal, assert_type
class Honest(tuple[int]):
    def __bool__(self) -> Literal[True]:
        return True
class FalseObject:
    def __bool__(self) -> Literal[False]:
        return False

def values(a: int, b: str) -> None:
    assert_type(a if Honest((1,)) else b, int)
    assert_type(a if FalseObject() else b, str)
    assert_type(a if (1,) else b, int)
    (a if FalseObject() else b).upper()

From that directory, run each built Pyright revision:

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

Base 2981f9f1ce41be5c15667da1f7a3cfda4f245089

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "invalid.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal['bad', 1]\" is not assignable to return type \"int\"\n  Type \"Literal['bad', 1]\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          23,
          11
        ],
        "end": [
          23,
          42
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[1, 'bad']\" is not assignable to return type \"int\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          14,
          11
        ],
        "end": [
          14,
          36
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[1, 'bad']\" is not assignable to return type \"int\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          17,
          11
        ],
        "end": [
          17,
          36
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[1, 'bad']\" is not assignable to return type \"int\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          20,
          11
        ],
        "end": [
          20,
          55
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "parameter-control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"upper\" for class \"int\"\n  Attribute \"upper\" is unknown",
      "range": {
        "start": [
          13,
          32
        ],
        "end": [
          13,
          37
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"int\" but received \"int | str\"",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          40
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"str\" but received \"int | str\"",
      "range": {
        "start": [
          11,
          16
        ],
        "end": [
          11,
          41
        ]
      }
    }
  ]
}

PR 68434643162acbe8b67da3eb5c62695d4168ea2c

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "invalid.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal['bad', 1]\" is not assignable to return type \"int\"\n  Type \"Literal['bad', 1]\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          23,
          11
        ],
        "end": [
          23,
          42
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "parameter-control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "valid.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.

Additional reproduction: Diagnostics changed for this example

The base and PR report different diagnostics for the same example. Is this change intended?

Create these files in an empty directory:

aliases.py

reveal_type(0)
import typing
from typing import TYPE_CHECKING as TC, Literal, assert_type
from typing_extensions import TYPE_CHECKING as EXTC

def aliases() -> None:
    reveal_type(typing.TYPE_CHECKING)
    reveal_type(TC)
    reveal_type(EXTC)

def shadow(TYPE_CHECKING: bool, a: int, b: str) -> None:
    assert_type(a if TYPE_CHECKING else b, int)

generic.py

reveal_type(0)
from typing import Literal, TypeVar, assert_type, overload, Annotated, Protocol
class FalseMeta(type):
    def __bool__(cls) -> Literal[False]:
        return False
class Base(metaclass=FalseMeta):
    pass
class Child(Base):
    pass
T = TypeVar('T', bound=Base)

def type_param(cls: type[T], a: int, b: str) -> None:
    assert_type(a if cls else b, str)
    (a if cls else b).upper()

def inherited(a: int, b: str) -> None:
    assert_type(a if Child else b, str)
    assert_type(Child or b, str)
    assert_type(Child and a, type[Child])

class Meta(type):
    def __bool__(cls) -> bool:
        return bool(id(cls) % 2)
class Dynamic(metaclass=Meta):
    pass

def dynamic(a: int, b: str) -> None:
    assert_type(a if Dynamic else b, int | str)

def combine(test: Annotated[bool, 'flag'], a: int, b: str) -> None:
    assert_type((a if test else b), int | str)

def exact_container(flag: Literal[True]) -> None:
    result = ('x',) if flag else (0,)
    assert_type(result, tuple[Literal['x']])
    rows = [result]
    rows.append(('x',))

pyrightconfig.json

{
  "include": [
    "tuple.py",
    "generic.py",
    "aliases.py"
  ],
  "pythonVersion": "3.13",
  "pythonPlatform": "Linux",
  "typeCheckingMode": "basic"
}

tuple.py

reveal_type(0)
from typing import Literal, NamedTuple, assert_type
class TruthyEmpty(tuple[()]):
    def __bool__(self) -> Literal[True]:
        return True
class FalsyFull(tuple[int]):
    def __bool__(self) -> Literal[False]:
        return False
class Record(NamedTuple):
    x: int
    def __bool__(self) -> Literal[False]:
        return False

def bad_empty() -> str:
    return 0 if TruthyEmpty() else 's' # E: reportReturnType

def bad_record() -> int:
    return 0 if Record(1) else 's' # E: reportReturnType

From that directory, run each built Pyright revision:

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

Base 2981f9f1ce41be5c15667da1f7a3cfda4f245089

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"EXTC\" is \"bool\"",
      "range": {
        "start": [
          8,
          16
        ],
        "end": [
          8,
          20
        ]
      }
    },
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"TC\" is \"bool\"",
      "range": {
        "start": [
          7,
          16
        ],
        "end": [
          7,
          18
        ]
      }
    },
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"typing.TYPE_CHECKING\" is \"bool\"",
      "range": {
        "start": [
          6,
          16
        ],
        "end": [
          6,
          36
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"upper\" for class \"int\"\n  Attribute \"upper\" is unknown",
      "range": {
        "start": [
          13,
          22
        ],
        "end": [
          13,
          27
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"int | str\" but received \"int\"",
      "range": {
        "start": [
          27,
          16
        ],
        "end": [
          27,
          35
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"str\" but received \"int\"",
      "range": {
        "start": [
          12,
          16
        ],
        "end": [
          12,
          31
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"str\" but received \"int\"",
      "range": {
        "start": [
          16,
          16
        ],
        "end": [
          16,
          33
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"str\" but received \"type[Child]\"",
      "range": {
        "start": [
          17,
          16
        ],
        "end": [
          17,
          26
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"tuple[Literal['x']]\" but received \"tuple[Literal['x']] | tuple[Literal[0]]\"",
      "range": {
        "start": [
          34,
          16
        ],
        "end": [
          34,
          22
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"type[Child]\" but received \"int\"",
      "range": {
        "start": [
          18,
          16
        ],
        "end": [
          18,
          27
        ]
      }
    },
    {
      "file": "tuple.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[0, 's']\" is not assignable to return type \"int\"\n  Type \"Literal[0, 's']\" is not assignable to type \"int\"\n    \"Literal['s']\" is not assignable to \"int\"",
      "range": {
        "start": [
          17,
          11
        ],
        "end": [
          17,
          34
        ]
      }
    },
    {
      "file": "tuple.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[0, 's']\" is not assignable to return type \"str\"\n  Type \"Literal[0, 's']\" is not assignable to type \"str\"\n    \"Literal[0]\" is not assignable to \"str\"",
      "range": {
        "start": [
          14,
          11
        ],
        "end": [
          14,
          38
        ]
      }
    },
    {
      "file": "tuple.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 68434643162acbe8b67da3eb5c62695d4168ea2c

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"EXTC\" is \"bool\"",
      "range": {
        "start": [
          8,
          16
        ],
        "end": [
          8,
          20
        ]
      }
    },
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"TC\" is \"bool\"",
      "range": {
        "start": [
          7,
          16
        ],
        "end": [
          7,
          18
        ]
      }
    },
    {
      "file": "aliases.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"typing.TYPE_CHECKING\" is \"bool\"",
      "range": {
        "start": [
          6,
          16
        ],
        "end": [
          6,
          36
        ]
      }
    },
    {
      "file": "generic.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "tuple.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[0, 's']\" is not assignable to return type \"str\"\n  Type \"Literal[0, 's']\" is not assignable to type \"str\"\n    \"Literal[0]\" is not assignable to \"str\"",
      "range": {
        "start": [
          14,
          11
        ],
        "end": [
          14,
          38
        ]
      }
    },
    {
      "file": "tuple.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.

Needs review: Diagnostics changed for this example

The base and PR report different diagnostics for the same example. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

control.py

reveal_type(0)
from typing import Literal, assert_type, final
@final
class Always:
    pass
class Falsy:
    def __bool__(self) -> Literal[False]:
        return False

def check(a: int, b: str) -> None:
    assert_type(a if Always() else b, int)
    assert_type(a if Falsy() else b, str)

main.py

reveal_type(0)
from typing import Literal
class Base:
    pass
class Falsy(Base):
    def __bool__(self) -> Literal[False]:
        return False

def make() -> Base:
    return Falsy()

def bad() -> int:
    return 1 if make() else 'bad' # E: reportReturnType

pyrightconfig.json

{
  "include": [
    "main.py",
    "control.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic"
}

From that directory, run each built Pyright revision:

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

Base 2981f9f1ce41be5c15667da1f7a3cfda4f245089

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "control.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"int\" but received \"int | str\"",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          36
        ]
      }
    },
    {
      "file": "control.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"str\" but received \"int | str\"",
      "range": {
        "start": [
          11,
          16
        ],
        "end": [
          11,
          35
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[1, 'bad']\" is not assignable to return type \"int\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          12,
          11
        ],
        "end": [
          12,
          33
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 68434643162acbe8b67da3eb5c62695d4168ea2c

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "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.

Additional reproduction: Diagnostics changed for this example

The base and PR report different diagnostics for the same example. Is this change intended?

Create these files in an empty directory:

control.py

reveal_type(0)
from main import Base, make

def parameter(x: Base) -> int:
    return 1 if x else 'bad'

def negated() -> int:
    return 'bad' if not make() else 1

main.py

reveal_type(0)
from typing import Literal
class Base:
    pass
class Intermediate(Base):
    pass
class Falsy(Intermediate):
    def __bool__(self) -> Literal[False]:
        return False
Alias = Base

def make() -> Alias:
    return Falsy()

def contextual_list() -> list[int]:
    return [1 if make() else 'bad'] # E: reportReturnType

def nested() -> int:
    return (1 if make() else 'bad') if True else 2 # E: reportReturnType

pyrightconfig.json

{
  "include": [
    "main.py",
    "control.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic"
}

From that directory, run each built Pyright revision:

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

Base 2981f9f1ce41be5c15667da1f7a3cfda4f245089

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal['bad', 1]\" is not assignable to return type \"int\"\n  Type \"Literal['bad', 1]\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          7,
          11
        ],
        "end": [
          7,
          37
        ]
      }
    },
    {
      "file": "control.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[1, 'bad']\" is not assignable to return type \"int\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          4,
          11
        ],
        "end": [
          4,
          28
        ]
      }
    },
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal[1, 'bad']\" is not assignable to return type \"int\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          18,
          11
        ],
        "end": [
          18,
          50
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"list[int | str]\" is not assignable to return type \"list[int]\"\n  Type \"Literal[1, 'bad']\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          15,
          12
        ],
        "end": [
          15,
          34
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 68434643162acbe8b67da3eb5c62695d4168ea2c

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Literal['bad', 1]\" is not assignable to return type \"int\"\n  Type \"Literal['bad', 1]\" is not assignable to type \"int\"\n    \"Literal['bad']\" is not assignable to \"int\"",
      "range": {
        "start": [
          7,
          11
        ],
        "end": [
          7,
          37
        ]
      }
    },
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    },
    {
      "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.

Other verified reproductions

Additional reproduction: reportGeneralTypeIssues no longer reported

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

Create these files in an empty directory:

main.py

reveal_type(0)
from collections import namedtuple
from typing import Literal
class Falsy(tuple[int]):
    def __bool__(self) -> Literal[False]:
        return False
Bad = namedtuple('Bad', ['def'], rename=Falsy((1,))) # E: reportGeneralTypeIssues

pyrightconfig.json

{
  "include": [
    "main.py"
  ],
  "pythonVersion": "3.13",
  "pythonPlatform": "Linux",
  "typeCheckingMode": "basic"
}

From that directory, run each built Pyright revision:

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

Base 2981f9f1ce41be5c15667da1f7a3cfda4f245089

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Falsy\" cannot be assigned to parameter \"rename\" of type \"bool\" in function \"namedtuple\"\n  \"Falsy\" is not assignable to \"bool\"",
      "range": {
        "start": [
          6,
          40
        ],
        "end": [
          6,
          51
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportGeneralTypeIssues",
      "message": "Field names cannot be a keyword",
      "range": {
        "start": [
          6,
          25
        ],
        "end": [
          6,
          30
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 68434643162acbe8b67da3eb5c62695d4168ea2c

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Falsy\" cannot be assigned to parameter \"rename\" of type \"bool\" in function \"namedtuple\"\n  \"Falsy\" is not assignable to \"bool\"",
      "range": {
        "start": [
          6,
          40
        ],
        "end": [
          6,
          51
        ]
      }
    },
    {
      "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.

@crypt0lith

crypt0lith commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

The first finding in #12057 (comment) (run: e7312d1) isn't new behavior -- it is in fact one of the oldest. evaluateStaticBoolExpression treats any name spelled TYPE_CHECKING as True, whatever it refers to, and has done so since 1d91744, pyright's third commit, first released in 1.0.0. The base already gives the parameter a literal type when it's assigned:

def check(TYPE_CHECKING: bool) -> None:
    x = TYPE_CHECKING
    reveal_type(x)
:3:17 - information: Type of "x" is "Literal[True]"

This PR applies that conversion to every expression, not only the right side of an assignment, so the argument case now shows it too.

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

2 participants