Skip to content

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

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

crypt0lith wants to merge 7 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
Fixes #12074
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].
  5. A non-empty tuple subclass, NamedTuple included, is treated as always truthy, even when its __bool__ returns Literal[False] or its __len__ isn't tuple's. Code after x or y on such an instance is unreachable.
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__.
  5. canBeFalsy decides a tuple subclass from its tuple length before looking up __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.
  5. Decide a tuple subclass's truthiness from its tuple length only when the class doesn't define __bool__ and its __len__ is tuple's. Look up __bool__ and __len__ on the class without instance attributes, as Python does.
    • Remove the __len__ that pyright synthesizes for namedtuple classes, which use tuple's at runtime.

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
Cases added to typeNarrowingFalsy1.py
Case Expected Description
func20 non-empty tuple subclass whose __bool__ returns Literal[False], only falsy
func21 NamedTuple whose __bool__ returns Literal[False], only falsy
func22 empty tuple subclass whose __bool__ returns Literal[True], only truthy
func23 non-empty tuple subclass whose __bool__ returns bool, either
func24 non-empty tuple subclass that overrides __len__, either
func25 NamedTuple that overrides __len__, either
func26 non-empty tuple subclass inheriting __len__ from a base before tuple in the MRO, either
func27 non-empty tuple subclass with a __len__ base after tuple in the MRO, only truthy
func28 non-empty functional namedtuple, only truthy
func29 class whose only __bool__ is an instance attribute, only truthy

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.

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, the other static condition and TypedDict tests, and every test whose sample uses a namedtuple; 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, or for a non-empty tuple subclass whose __bool__ or __len__ does. A class whose only __bool__ is an instance attribute is always truthy, as at runtime.

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 — 7a48423e — verdict: red

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

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:

invalid.py

from typing import Literal
reveal_type(0)
class UserPlatform:
    platform: str = "win32"
def wrong(sys: UserPlatform) -> Literal[False]:
    return sys.platform == "win32"

pyrightconfig.json

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

valid.py

from typing import assert_type
reveal_type(0)
class UserPlatform:
    platform: str = "win32"
def check(sys: UserPlatform) -> None:
    assert_type(sys.platform == "win32", bool)

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 \"bool\" is not assignable to return type \"Literal[False]\"\n  \"bool\" is not assignable to type \"Literal[False]\"",
      "range": {
        "start": [
          5,
          11
        ],
        "end": [
          5,
          34
        ]
      }
    },
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 7a48423edd28856363e32468f0353aaa9696488f

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "invalid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "valid.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"bool\" but received \"Literal[False]\"",
      "range": {
        "start": [
          5,
          16
        ],
        "end": [
          5,
          39
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

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)
class Zero(tuple[int]):
    def __len__(self) -> int: return 0
def wrong(a: int, b: str) -> int:
    return a if Zero((1,)) else b

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 \"int | str\" is not assignable to return type \"int\"\n  Type \"int | str\" is not assignable to type \"int\"\n    \"str\" is not assignable to \"int\"",
      "range": {
        "start": [
          4,
          11
        ],
        "end": [
          4,
          33
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          0,
          12
        ],
        "end": [
          0,
          13
        ]
      }
    }
  ]
}

PR 7a48423edd28856363e32468f0353aaa9696488f

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

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

@crypt0lith

crypt0lith commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

The tuple-subclass findings in #12057 (comment) (run: 6843464) aren't new behavior. The base's and and or already treat such an instance as always truthy, and this PR decides the ternary and namedtuple's rename argument the same way, so those cases now show it too. I opened #12074 to track the bug and fixed it here in 7a48423.

The make() -> Base findings aren't a defect that can be easily reconciled. canBeFalsy treats an instance of any class other than object with no __bool__ or __len__ as always truthy (evaluatorNarrowing.ts:177), and the base's or already relies on it:

class Base:
    pass


def f(x: Base):
    reveal_type(x or "x")
:6:17 - information: Type of "x or "x"" is "Base"

object.__bool__ is always true in CPython:

>>> bool(object())
True

The comment on that check already calls out the gap (evaluatorNarrowing.ts:171-176): a non-final class could be overridden to be falsy, and being fully correct would mean returning !ClassType.isFinal(type). So the bot is holding this PR to a case pyright already documents as a known gap. Pyright would need to fully model intersection types to respect @final there without breaking everything else.

@github-actions

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

sympy (https://github.com/sympy/sympy)
-   .../projects/sympy/sympy/concrete/summations.py:1389:12 - error: Operator "*" not supported for types "Expr | Basic | Any | Unknown" and "Basic"
+   .../projects/sympy/sympy/concrete/summations.py:1389:12 - error: Operator "*" not supported for types "Expr | Unknown" and "Basic"
-     Operator "*" not supported for types "Expr" and "Basic"
-     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:468:32 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:469:28 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:473:23 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:474:24 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:478:25 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:480:40 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:481:54 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:484:54 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:485:40 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:487:55 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:488:41 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:489:41 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:490:55 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:493:20 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:494:35 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:496:21 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:499:19 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:500:25 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:502:25 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:504:20 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:506:26 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:510:22 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:513:29 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:514:30 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:519:14 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:520:14 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:523:14 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:524:14 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:535:14 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:538:14 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:543:14 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:544:14 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:547:14 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:548:14 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:587:27 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+   .../projects/sympy/sympy/core/tests/test_exprtools.py:588:28 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
-   .../projects/sympy/sympy/integrals/meijerint.py:1491:13 - error: Index 0 is out of range for type tuple[()] (reportGeneralTypeIssues)
-   .../projects/sympy/sympy/integrals/meijerint.py:1493:18 - error: Cannot access attribute "base" for class "Expr"
-     Attribute "base" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/integrals/meijerint.py:1493:37 - error: Cannot access attribute "exp" for class "Expr"
-     Attribute "exp" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/integrals/tests/test_meijerint.py:496:23 - error: Argument of type "Unknown | Basic" cannot be assigned to parameter "expr" of type "Expr" in function "expand_mul"
-     Type "Unknown | Basic" is not assignable to type "Expr"
-       "Basic" is not assignable to "Expr" (reportArgumentType)
-   .../projects/sympy/sympy/polys/rootoftools.py:1197:26 - error: Operator "*" not supported for types "int" and "Basic | Unknown | Self@RootSum | Expr"
-     Operator "*" not supported for types "int" and "Basic" (reportOperatorIssue)
- .../projects/sympy/sympy/series/limitseq.py
-   .../projects/sympy/sympy/series/limitseq.py:134:25 - error: Cannot access attribute "as_numer_denom" for class "Basic"
-     Attribute "as_numer_denom" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/series/limitseq.py:149:25 - error: Cannot access attribute "as_numer_denom" for class "Basic"
-     Attribute "as_numer_denom" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/simplify/fu.py:994:35 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
-     Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
-       "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
-         Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
-           "Basic" is not assignable to "Expr" (reportArgumentType)
-   .../projects/sympy/sympy/simplify/fu.py:1006:39 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
-     Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
-       "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
-         Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
-           "Basic" is not assignable to "Expr" (reportArgumentType)
-   .../projects/sympy/sympy/simplify/fu.py:1028:43 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
-     Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
-       "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
-         Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
-           "Basic" is not assignable to "Expr" (reportArgumentType)
-   .../projects/sympy/sympy/simplify/fu.py:1039:47 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
-     Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
-       "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
-         Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
-           "Basic" is not assignable to "Expr" (reportArgumentType)
-   .../projects/sympy/sympy/simplify/simplify.py:166:20 - error: Argument of type "dict[str, Unknown] | dict[Unknown, list[Unknown]] | Expr | Abs | Unknown | Basic | None" cannot be assigned to parameter "b" of type "Expr | complex" in function "__new__"

... (truncated 193 lines) ...

scikit-learn (https://github.com/scikit-learn/scikit-learn)
-   .../projects/scikit-learn/sklearn/linear_model/_least_angle.py:803:34 - error: Argument of type "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" cannot be assigned to parameter "key" of type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" in function "__getitem__"
+   .../projects/scikit-learn/sklearn/linear_model/_least_angle.py:803:34 - error: Argument of type "tuple[slice[None, int, None], slice[int, None, None]]" cannot be assigned to parameter "key" of type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" in function "__getitem__"
-     Type "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" is not assignable to type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]"
+     Type "tuple[slice[None, int, None], slice[int, None, None]]" is not assignable to type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]"
-       "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" is incompatible with protocol "SupportsIndex"
+       "tuple[slice[None, int, None], slice[int, None, None]]" is incompatible with protocol "SupportsIndex"
-       "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" is not assignable to "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" (reportArgumentType)
+       "tuple[slice[None, int, None], slice[int, None, None]]" is not assignable to "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" (reportArgumentType)

pandera (https://github.com/pandera-dev/pandera)
-   .../projects/pandera/pandera/api/pandas/model.py:290:68 - error: Argument of type "dict[str, Any | str | None]" cannot be assigned to parameter "dtype" of type "AstypeArg | Mapping[Any, Dtype] | Series[Any]" in function "astype"
-     Type "dict[str, Any | str | None]" is not assignable to type "AstypeArg | Mapping[Any, Dtype] | Series[Any]"
-       Type "dict[str, Any | str | None]" is not assignable to type "type[bool]"
-       "dict[str, Any | str | None]" is not assignable to "BooleanDtype"
-       Type "dict[str, Any | str | None]" is not assignable to type "type[numpy.bool[builtins.bool]]"
-       Type "dict[str, Any | str | None]" is not assignable to type "type[int]"
-       "dict[str, Any | str | None]" is not assignable to "Int8Dtype"
-       "dict[str, Any | str | None]" is not assignable to "Int16Dtype"
-       "dict[str, Any | str | None]" is not assignable to "Int32Dtype"
-     ... (reportArgumentType)
- 3858 errors, 201 warnings, 0 informations
+ 3857 errors, 201 warnings, 0 informations

apprise (https://github.com/caronc/apprise)
-     Return type mismatch: base method returns type "Literal[1]", override returns type "int"
+     Return type mismatch: base method returns type "Literal[1]", override returns type "Literal[0]"
-       "int" is not assignable to type "Literal[1]" (reportIncompatibleMethodOverride)
+       "Literal[0]" is not assignable to type "Literal[1]" (reportIncompatibleMethodOverride)
+   .../projects/apprise/apprise/attachment/memory.py:213:9 - error: Method "__len__" overrides class "AttachBase" in an incompatible manner
+     Return type mismatch: base method returns type "Literal[0]", override returns type "int"
+       "int" is not assignable to type "Literal[0]" (reportIncompatibleMethodOverride)
- 7486 errors, 18 warnings, 0 informations
+ 7487 errors, 18 warnings, 0 informations

dd-trace-py (https://github.com/DataDog/dd-trace-py)
-   .../projects/dd-trace-py/tests/debugging/exploration/_profiler.py:58:39 - error: Cannot access attribute "__code__" for class "FullyNamedFunction"
-     Attribute "__code__" is unknown (reportAttributeAccessIssue)
-     Attribute "_encoders" is unknown (reportAttributeAccessIssue)
-   .../projects/dd-trace-py/tests/debugging/exploration/debugger.py:144:23 - error: Cannot assign to attribute "_encoders" for class "NoopSnapshotJsonEncoder"
- 13573 errors, 765 warnings, 0 informations
+ 13571 errors, 765 warnings, 0 informations

spack (https://github.com/spack/spack)
-   .../projects/spack/lib/spack/spack/test/traverse.py:497:23 - error: Cannot access attribute "parent" for class "tuple[int, DependencySpec]"
-     Attribute "parent" is unknown (reportAttributeAccessIssue)
-   .../projects/spack/lib/spack/spack/test/traverse.py:497:48 - error: Cannot access attribute "parent" for class "tuple[int, DependencySpec]"
-     Attribute "parent" is unknown (reportAttributeAccessIssue)
-     Attribute "spec" is unknown (reportAttributeAccessIssue)
-   .../projects/spack/lib/spack/spack/test/traverse.py:497:66 - error: Cannot access attribute "spec" for class "tuple[int, DependencySpec]"
- 1891 errors, 20 warnings, 0 informations
+ 1888 errors, 20 warnings, 0 informations

jax (https://github.com/google/jax)
-   .../projects/jax/jax/experimental/sparse/bcoo.py:418:25 - error: "int" is not iterable
+   .../projects/jax/jax/experimental/sparse/bcoo.py:418:25 - error: "Literal[1]" is not iterable
-   .../projects/jax/jax/experimental/sparse/bcoo.py:1418:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | int" cannot be assigned to target tuple
+   .../projects/jax/jax/experimental/sparse/bcoo.py:1418:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | Literal[1]" cannot be assigned to target tuple
-   .../projects/jax/jax/experimental/sparse/bcoo.py:1418:39 - error: "int" is not iterable
+   .../projects/jax/jax/experimental/sparse/bcoo.py:1418:39 - error: "Literal[1]" is not iterable
-   .../projects/jax/jax/experimental/sparse/bcoo.py:1534:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | int" cannot be assigned to target tuple
+   .../projects/jax/jax/experimental/sparse/bcoo.py:1534:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | Literal[1]" cannot be assigned to target tuple
-   .../projects/jax/jax/experimental/sparse/bcoo.py:1534:39 - error: "int" is not iterable
+   .../projects/jax/jax/experimental/sparse/bcoo.py:1534:39 - error: "Literal[1]" is not iterable

alerta (https://github.com/alerta/alerta)
-   .../projects/alerta/alerta/database/backends/postgres/base.py:349:105 - error: "attributes" is not a known attribute of "None" (reportOptionalMemberAccess)
-   .../projects/alerta/alerta/database/backends/postgres/base.py:369:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
-   .../projects/alerta/alerta/database/backends/postgres/base.py:379:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
-   .../projects/alerta/alerta/database/backends/postgres/base.py:388:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
-   .../projects/alerta/alerta/database/backends/postgres/base.py:397:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
- 521 errors, 15 warnings, 0 informations
+ 516 errors, 15 warnings, 0 informations

@github-actions

Copy link
Copy Markdown
Contributor

mypy_primer analysis

Advisory AI analysis of primer run 46478689026, attempt 1
for commit 7a48423edd28856363e32468f0353aaa9696488f. This is not an approval or proof of correctness.

Regression review required. Potential regressions or recorded warning signals are listed first; causation must be established separately.

Potential regressions

sympy: Truthiness-driven branch pruning reshapes many unions and removes several independent attribute, optional, and operator checks; the mixed gains do not establish that the lost checks were unreachable.

Regression warning signals require review, regardless of the AI assessment:

  • Type-checking diagnostics disappear without replacements at the same locations.
  • Changed diagnostic details introduce Any/Unknown.

AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: The recorded baseline checked both sides of affected flows: e.g. meijerint.py:1491 rejected indexing tuple[()], sqrtdenest.py:303 rejected multiplication by None, single.py:2757 rejected subscripting None, and several Basic-vs-Expr/member errors were reported. These are observed diagnostics, not inferred runtime failures.

After / PR evidence: The three highlighted checks disappear. Elsewhere the same run gains None-member checks in test_exprtools.py:468-588 and much wider operator/member diagnostics around sqrtdenest.py:340-635; at sqrtdenest.py:309 a new Expr + (... | None) error partly replaces the old line-303 optional-operand error. This is redistribution of checked paths, not a simple cleanup.

Why this matters: Users can no longer rely on Pyright to flag the tuple index, optional subscript, and some Basic member/argument operations on these paths. Conversely, newly reachable paths now expose many optional/member/operator errors. If a condition is not actually invariant, suppressing one branch can hide real static errors without any runtime regression being required.

Causal analysis:

The PR changes ternary evaluation to call canBeFalsy/canBeTruthy and omit an arm when a condition's type is one-sided, changes truthiness to honor __bool__ before tuple length/__len__, and gives statically evaluated boolean expressions literal types. Those choices feed later flow and expression inference, explaining both narrower unions (Basic disappears at simplify.py:166 and Unknown disappears from summations.py:1389) and newly/previously analyzed branches. The removed checks are credible regressions because no inspected evidence proves their guards constant; the simultaneous new checks are counterevidence to a blanket regression classification but do not restore the lost operations. No type-erasure or assertion-failure signal was recorded; the gradual-detail signal instead shows union-member replacement. The exact ecosystem revision and synthetic merge SHA were unavailable, so current SymPy source was not treated as historical proof.

Uncertainty / next check: At each removed site, test the recorded source with a condition type whose __bool__ returns plain bool versus Literal[True]/Literal[False]. A negative control should keep both arms and retain the None/tuple/member error; a positive control with a literal truth value should prune only the impossible arm.

  • Exact PR head: ternaries now use type truthiness and may omit an arm.:
    evaluator: TypeEvaluator,
    node: TernaryNode,
    flags: EvalFlags,
    inferenceContext: InferenceContext | undefined
    ): TypeResult {
    if ((flags & EvalFlags.TypeExpression) !== 0) {
    evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.ternaryNotAllowed(), node);
    return { type: UnknownType.create() };
    }
    const testTypeResult = evaluator.getTypeOfExpression(node.d.testExpr);
    const typesToCombine: Type[] = [];
    let isIncomplete = false;
    let typeErrors = false;
    let constExprValue: boolean | undefined;
    if (!testTypeResult.isIncomplete) {
    if (!evaluator.canBeFalsy(testTypeResult.type)) {
    constExprValue = true;
    } else if (!evaluator.canBeTruthy(testTypeResult.type)) {
    constExprValue = false;
    }
    }
    if (constExprValue !== false && evaluator.isNodeReachable(node.d.ifExpr)) {
    const ifType = evaluator.getTypeOfExpression(node.d.ifExpr, flags, inferenceContext);
    typesToCombine.push(ifType.type);
    if (ifType.isIncomplete) {
    isIncomplete = true;
    }
  • Exact PR head: __bool__, tuple length, and __len__ truthiness precedence changed.:
    }
    case TypeCategory.Class: {
    // The truthiness of a class object is determined by its metaclass.
    if (TypeBase.isInstantiable(type)) {
    const metaclass = type.shared.effectiveMetaclass;
    return (
    !!metaclass &&
    isInstantiableClass(metaclass) &&
    canBeFalsy(ClassType.cloneAsInstance(metaclass), recursionCount)
    );
    }
    // Sentinels are always truthy.
    if (isSentinelLiteral(type)) {
    return false;
    }
    // Handle tuples specially.
    if (isTupleClass(type) && type.priv.tupleTypeArgs) {
    return isUnboundedTupleClass(type) || type.priv.tupleTypeArgs.length === 0;
    }
    // Handle subclasses of tuple, such as NamedTuple, that don't define __bool__.
    const tupleBaseClass = type.shared.mro.find((mroClass) => !isClass(mroClass) || isTupleClass(mroClass));
    if (
    tupleBaseClass &&
    isClass(tupleBaseClass) &&
    tupleBaseClass.priv.tupleTypeArgs &&
    !lookUpObjectMember(type, '__bool__')
    ) {
    return isUnboundedTupleClass(tupleBaseClass) || tupleBaseClass.priv.tupleTypeArgs.length === 0;
    }
    // Handle TypedDicts specially. If one or more entries are required
    // or known to exist, we can say for sure that the type is not falsy.
    if (ClassType.isTypedDictClass(type)) {
    const tdEntries = getTypedDictMembersForClass(evaluatorInterface, type, /* allowNarrowed */ true);
    if (tdEntries) {
    for (const tdEntry of tdEntries.knownItems.values()) {
    if (tdEntry.isRequired || tdEntry.isProvided) {
    return false;
    }
    }
    }
    }
    // Check for bool, int, str and bytes literals that are never falsy.
    if (type.priv.literalValue !== undefined) {
    if (ClassType.isBuiltIn(type, ['bool', 'int', 'str', 'bytes'])) {
    return !type.priv.literalValue || type.priv.literalValue === BigInt(0);
    }
    if (type.priv.literalValue instanceof EnumLiteral) {
    // Does the Enum class forward the truthiness check to the
    // underlying member type?
    if (type.priv.literalValue.isReprEnum) {
    return canBeFalsy(type.priv.literalValue.itemType, recursionCount);
    }
    }
    }
    // If this is a protocol class, don't make any assumptions about the absence
    // of specific methods. These could be provided by a class that conforms
    // to the protocol.
    if (ClassType.isProtocolClass(type)) {
    return true;
    }
    const boolMethod = lookUpObjectMember(type, '__bool__');
    if (boolMethod) {
    const boolMethodType = getTypeOfMember(boolMethod);
    // If the __bool__ function unconditionally returns True, it can never be falsy.
    if (isFunction(boolMethodType) && boolMethodType.shared.declaredReturnType) {
    const returnType = boolMethodType.shared.declaredReturnType;
    if (
    isClassInstance(returnType) &&
    ClassType.isBuiltIn(returnType, 'bool') &&
    returnType.priv.literalValue === true
    ) {
    return false;
    }
    }
    return true;
    }
    // Truthiness falls back to __len__ only if __bool__ isn't defined.
    const lenMethod = lookUpObjectMember(type, '__len__');
    if (lenMethod) {
    return true;
  • PR tests intentionally expect one-arm ternary types for statically truthy/falsy callable, None, metaclass, enum, and __bool__ cases.:
    def func1(f: Callable[[], None], a: int, b: str) -> None:
    assert_type(a if f else b, int)
    def func2(n: None, a: int, b: str) -> None:
    assert_type(a if n else b, str)
    def func3(flag: bool, a: int, b: str) -> None:
    assert_type(a if flag else b, int | str)
    class Meta(type):
    def __bool__(cls) -> Literal[False]:
    return False
    class FalsyClass(metaclass=Meta):
    pass
    class Color(Enum):
    RED = 1
    class TruthyWithLen:
    def __bool__(self) -> Literal[True]:
    return True
    def __len__(self) -> int:
    return 0
    def func4(a: int, b: str) -> None:
    assert_type(a if FalsyClass else b, str)
    def func5(a: int, b: str) -> None:
    assert_type(a if Color else b, int)
    def func6(a: int, b: str) -> None:
    assert_type(a if TruthyWithLen else b, int)
    def func7(t: TruthyWithLen, a: int, b: str) -> None:
    assert_type(a if t else b, int)

pandera: An astype mapping error disappears after a conditional dtype value loses its None alternative; without the recorded checkout, it is unclear whether that branch is truly impossible.

AI assessment: Possible regression (low confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At model.py:290:68, the baseline rejected dict[str, Any | str | None] as pandas astype's dtype argument and gave detailed incompatibilities with AstypeArg/Mapping[Any, Dtype]/Series[Any]. This was an observed argument check.

After / PR evidence: The entire argument diagnostic and its detail disappear. Current upstream has a dtypes comprehension with a conditional value followed by DataFrame(...).astype(dtypes), consistent with a ternary precision change, but current source is not proof of the recorded revision.

Why this matters: A caller can no longer rely on Pyright to reject a dtype mapping whose values may include None at this site. If None is genuinely excluded by the condition, this is a useful false-positive removal; if not, the PR has suppressed validation of an invalid mapping.

Causal analysis:

The PR's ternary path now uses canBeFalsy/canBeTruthy and skips an arm when the condition type is considered one-sided. That can remove the else-None member from a comprehension value, after which Any in the remaining value union can make astype's overload acceptable. This is not evidence of type erasure of the outer dict, but it can still weaken argument checking. Current Pandera source shows the same structural pattern, yet the exact ecosystem commit and synthetic Pyright merge were unavailable. Because no declaration proving the condition always truthy was inspected at the recorded revision, blaming pandas stubs or calling the removal expected would be premature.

Uncertainty / next check: Resolve the recorded Pandera commit and inspect the type and truth methods of the comprehension condition. Control with T | None must retain None and the astype error; a non-optional, provably truthy T should select only the dtype arm.

  • Exact PR head prunes ternary arms based on inferred truthiness.:
    evaluator: TypeEvaluator,
    node: TernaryNode,
    flags: EvalFlags,
    inferenceContext: InferenceContext | undefined
    ): TypeResult {
    if ((flags & EvalFlags.TypeExpression) !== 0) {
    evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.ternaryNotAllowed(), node);
    return { type: UnknownType.create() };
    }
    const testTypeResult = evaluator.getTypeOfExpression(node.d.testExpr);
    const typesToCombine: Type[] = [];
    let isIncomplete = false;
    let typeErrors = false;
    let constExprValue: boolean | undefined;
    if (!testTypeResult.isIncomplete) {
    if (!evaluator.canBeFalsy(testTypeResult.type)) {
    constExprValue = true;
    } else if (!evaluator.canBeTruthy(testTypeResult.type)) {
    constExprValue = false;
    }
    }
    if (constExprValue !== false && evaluator.isNodeReachable(node.d.ifExpr)) {
    const ifType = evaluator.getTypeOfExpression(node.d.ifExpr, flags, inferenceContext);
    typesToCombine.push(ifType.type);
    if (ifType.isIncomplete) {
    isIncomplete = true;
    }
  • Current upstream, not the recorded revision, shows a conditional dtype comprehension passed to astype; it supports the mechanism but not historical identity.: https://github.com/pandera-dev/pandera/blob/fcfc82153be128300055996cde7db2c34990e357/pandera/api/pandas/model.py#L280-L291

apprise: Literal return inference for inherited __len__ methods becomes subclass-dependent, producing a new override error and changing the old mismatch from int to Literal[0].

AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: One override mismatch said a base __len__ returned Literal[1] while the override returned int. This is observed diagnostic detail, not an assertion expectation.

After / PR evidence: That mismatch now says the override returns Literal[0], and memory.py:213:9 gains a second error because AttachMemory.__len__ returns int while its base is inferred as Literal[0]. Current AttachMemory explicitly returns its buffer size, an arbitrary nonnegative int.

Why this matters: Valid subclasses whose lengths vary can be rejected as incompatible because a base implementation's ternary result is specialized to one literal under the subclass's truthiness. Users can no longer rely on ordinary int-returning __len__ overrides being compared against the base's unspecialized int contract.

Causal analysis:

The PR makes ternaries one-armed when canBeFalsy/canBeTruthy says their condition is constant and changes __bool__/__len__ precedence. A base __len__ implemented as `1 if self else 0` can therefore infer Literal[1] or Literal[0] rather than int, and inherited analysis appears to vary with subclass truthiness; the changed and additional override diagnostics are the direct symptom. The PR's own tuple-literal test expects this kind of literal narrowing, but applying it to an overridable method contract is counterevidence to treating the ecosystem errors as an unqualified improvement. Current source confirms AttachMemory's varying int length, though the exact analyzed Apprise commit is unavailable.

Uncertainty / next check: Minimal control: base `def __len__(self): return 1 if self else 0`, subclass `__bool__ -> Literal[False]`, and subclass `__len__ -> int`. Compare method's declared/inferred contract with call-site specialization; only the call result, not override compatibility, should specialize.

  • Exact PR head specializes ternary result arms from condition truthiness.:
    evaluator: TypeEvaluator,
    node: TernaryNode,
    flags: EvalFlags,
    inferenceContext: InferenceContext | undefined
    ): TypeResult {
    if ((flags & EvalFlags.TypeExpression) !== 0) {
    evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.ternaryNotAllowed(), node);
    return { type: UnknownType.create() };
    }
    const testTypeResult = evaluator.getTypeOfExpression(node.d.testExpr);
    const typesToCombine: Type[] = [];
    let isIncomplete = false;
    let typeErrors = false;
    let constExprValue: boolean | undefined;
    if (!testTypeResult.isIncomplete) {
    if (!evaluator.canBeFalsy(testTypeResult.type)) {
    constExprValue = true;
    } else if (!evaluator.canBeTruthy(testTypeResult.type)) {
    constExprValue = false;
    }
    }
    if (constExprValue !== false && evaluator.isNodeReachable(node.d.ifExpr)) {
    const ifType = evaluator.getTypeOfExpression(node.d.ifExpr, flags, inferenceContext);
    typesToCombine.push(ifType.type);
    if (ifType.isIncomplete) {
    isIncomplete = true;
    }
  • Exact PR head changes how __bool__ and __len__ determine one-sided truthiness.:
    return isUnboundedTupleClass(type) || type.priv.tupleTypeArgs.length === 0;
    }
    // Handle subclasses of tuple, such as NamedTuple, that don't define __bool__.
    const tupleBaseClass = type.shared.mro.find((mroClass) => !isClass(mroClass) || isTupleClass(mroClass));
    if (
    tupleBaseClass &&
    isClass(tupleBaseClass) &&
    tupleBaseClass.priv.tupleTypeArgs &&
    !lookUpObjectMember(type, '__bool__')
    ) {
    return isUnboundedTupleClass(tupleBaseClass) || tupleBaseClass.priv.tupleTypeArgs.length === 0;
    }
    // Handle TypedDicts specially. If one or more entries are required
    // or known to exist, we can say for sure that the type is not falsy.
    if (ClassType.isTypedDictClass(type)) {
    const tdEntries = getTypedDictMembersForClass(evaluatorInterface, type, /* allowNarrowed */ true);
    if (tdEntries) {
    for (const tdEntry of tdEntries.knownItems.values()) {
    if (tdEntry.isRequired || tdEntry.isProvided) {
    return false;
    }
    }
    }
    }
    // Check for bool, int, str and bytes literals that are never falsy.
    if (type.priv.literalValue !== undefined) {
    if (ClassType.isBuiltIn(type, ['bool', 'int', 'str', 'bytes'])) {
    return !type.priv.literalValue || type.priv.literalValue === BigInt(0);
    }
    if (type.priv.literalValue instanceof EnumLiteral) {
    // Does the Enum class forward the truthiness check to the
    // underlying member type?
    if (type.priv.literalValue.isReprEnum) {
    return canBeFalsy(type.priv.literalValue.itemType, recursionCount);
    }
    }
    }
    // If this is a protocol class, don't make any assumptions about the absence
    // of specific methods. These could be provided by a class that conforms
    // to the protocol.
    if (ClassType.isProtocolClass(type)) {
    return true;
    }
    const boolMethod = lookUpObjectMember(type, '__bool__');
    if (boolMethod) {
    const boolMethodType = getTypeOfMember(boolMethod);
    // If the __bool__ function unconditionally returns True, it can never be falsy.
    if (isFunction(boolMethodType) && boolMethodType.shared.declaredReturnType) {
    const returnType = boolMethodType.shared.declaredReturnType;
    if (
    isClassInstance(returnType) &&
    ClassType.isBuiltIn(returnType, 'bool') &&
    returnType.priv.literalValue === true
    ) {
    return false;
    }
    }
    return true;
    }
    // Truthiness falls back to __len__ only if __bool__ isn't defined.
    const lenMethod = lookUpObjectMember(type, '__len__');
    if (lenMethod) {
    return true;
  • Current upstream AttachMemory returns a buffer byte count from __len__, then defines __bool__; exact analyzed revision was not resolved.: https://github.com/caronc/apprise/blob/03bb80cc851182d342edbd4e663c2d2ce57aa242/apprise/attachment/memory.py#L210-L217

dd-trace-py: Two attribute checks disappear on live exploration-code paths, consistent with truthiness-based branch elimination rather than corrected member types.

AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: The baseline rejected `f.__code__` at _profiler.py:58:39 because f could be FullyNamedFunction, and rejected assignment to `_encoders` at debugger.py:144:23 for NoopSnapshotJsonEncoder. Both were concrete attribute-access checks.

After / PR evidence: Both diagnostics vanish with no replacement detail and no evidence that the relevant class declarations acquired those members. Current upstream retains analogous accesses, but its revision is not the recorded primer checkout.

Why this matters: Users can no longer rely on Pyright to flag an unsupported function-code attribute or private encoder assignment along these paths. If the condition selecting these paths is not statically fixed, real member mistakes are hidden even though runtime may still happen to work dynamically.

Causal analysis:

The PR converts static boolean expressions to Literal booleans and lets ternary/control-flow reachability consume declared or Final conditions, while truthiness analysis now gives __bool__ precedence. Any configuration or version guard around these exploration paths can therefore become statically one-sided, preventing the member operation from being evaluated. The removed diagnostics are not explained by a stub correction in the PR. However, the raw diff omits unchanged context and the exact dd-trace revision was unavailable, so the precise guarding expression could not be established. That uncertainty prevents a high-confidence causal claim but leaves a credible checker regression.

Uncertainty / next check: Resolve the recorded commit and inspect guards around both statements. Negative control with an unconstrained bool must preserve each attribute error; positive control with a valid Final/static platform condition may suppress only the unreachable branch.

  • Exact PR head assigns literal bool types to statically evaluated conditions.:
    validateTypeIsInstantiable(typeResult, flags, node);
    }
    // If this is a constant boolean expression, assign it a literal type.
    if (
    (node.nodeType === ParseNodeType.Name ||
    node.nodeType === ParseNodeType.MemberAccess ||
    node.nodeType === ParseNodeType.UnaryOperation ||
    node.nodeType === ParseNodeType.BinaryOperation) &&
    (flags & EvalFlags.TypeExpression) === 0 &&
    isClassInstance(typeResult.type) &&
    ClassType.isBuiltIn(typeResult.type, 'bool') &&
    (typeResult.type.priv.literalValue === undefined ||
    (node.nodeType === ParseNodeType.Name && node.d.value === 'TYPE_CHECKING')) &&
    areTypeCheckingNamesValid(node)
    ) {
    const fileInfo = nodeInfo.getFileInfo(node);
    const constExprValue = evaluateStaticBoolExpression(
    node,
    fileInfo.executionEnvironment,
    fileInfo.definedConstants
    );
    if (constExprValue !== undefined) {
    typeResult = { ...typeResult, type: ClassType.cloneWithLiteral(typeResult.type, constExprValue) };
    }
    }
    // If this is a PEP 695 type alias, remove the special form so the type
    // printer prints it as its aliased type rather than TypeAliasType.
    if ((flags & EvalFlags.TypeExpression) !== 0 && typeResult.type.props?.typeForm === undefined) {
    const specialForm = typeResult.type.props?.specialForm;
    if (specialForm && ClassType.isBuiltIn(specialForm, 'TypeAliasType')) {
    typeResult.type = TypeBase.cloneAsSpecialForm(typeResult.type, undefined);
    }
    }
    return typeResult;
    }
    // Determines whether each name spelled TYPE_CHECKING within a static condition
    // refers to typing's TYPE_CHECKING or to a variable assigned False.
    function areTypeCheckingNamesValid(node: ExpressionNode): boolean {
    switch (node.nodeType) {
    case ParseNodeType.Name: {
    if (node.d.value !== 'TYPE_CHECKING') {
    return true;
    }
    const decls =
    lookUpSymbolRecursive(node, node.d.value, /* honorCodeFlow */ false)?.symbol.getDeclarations() ??
    [];
    return (
    decls.length > 0 &&
    decls.every((decl) => {
    const resolvedDecl = resolveAliasDeclaration(decl, /* resolveLocalNames */ true);
    if (resolvedDecl?.type !== DeclarationType.Variable) {
    return false;
    }
    if (resolvedDecl.moduleName === 'typing') {
    return true;
    }
    const source = resolvedDecl.inferredTypeSource;
    return source?.nodeType === ParseNodeType.Constant && source.d.constType === KeywordType.False;
    })
    );
    }
  • Exact PR head marks branches unreachable from declared/Final condition references.:
    ) {
    const conditionalFlowNode = curFlowNode as FlowCondition;
    if (conditionalFlowNode.reference) {
    const referenceDeclKind = getConditionReferenceDeclKind(conditionalFlowNode.reference);
    if (referenceDeclKind !== undefined) {
    let unreachability: Reachability | undefined;
    const typeNarrowingCallback = getTypeNarrowingCallback(
    evaluator,
    conditionalFlowNode.reference!,
    conditionalFlowNode.expression,
    !!(
    conditionalFlowNode.flags &
    (FlowFlags.TrueCondition | FlowFlags.TrueNeverCondition)
    ),
    nodeInfo
    );
    if (typeNarrowingCallback) {
    const refTypeInfo = evaluator.getTypeOfExpression(conditionalFlowNode.reference!);
    const narrowedTypeResult = applyTypeNarrowingCallback(
    typeNarrowingCallback,
    refTypeInfo.type
    );
    const narrowedType = narrowedTypeResult?.type ?? refTypeInfo.type;
    if (isNever(narrowedType) && !refTypeInfo.isIncomplete) {
    // A Final with a literal type is treated like a
    // statically-evaluated condition.
    unreachability =
    referenceDeclKind === ConditionReferenceDeclKind.Final &&
    isClassInstance(refTypeInfo.type) &&
    isLiteralType(refTypeInfo.type)
    ? Reachability.UnreachableStaticCondition
    : Reachability.UnreachableByAnalysis;
    }
  • Current upstream retains the resolved object's __code__ accesses; this is corroboration only, not the recorded revision.: https://github.com/DataDog/dd-trace-py/blob/8e337d94a536c93c3b9b9097540f4decbdcfa274/tests/debugging/exploration/_profiler.py#L42-L60

spack: All member errors on a tuple-or-edge value disappear together, suggesting one union arm or branch was pruned without evidence that tuple values are impossible.

AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At traverse.py:497, the baseline reported two `.parent` accesses and one `.spec` access on tuple[int, DependencySpec]. The tuple outer type was preserved, so these checks caught a concrete API mismatch rather than element imprecision.

After / PR evidence: All three attribute diagnostics disappear and no replacement is recorded. The evidence does not show that the value was retyped to an edge object or that the tuple alternative became unreachable.

Why this matters: Downstream code can no longer rely on Pyright to reject edge-style member access when the value may still be a `(depth, edge)` tuple. This loses checks for the tuple's outer API, not merely a generic argument.

Causal analysis:

The PR's reachability and ternary changes can discard one alternative when a condition is inferred always truthy/falsy, and its truthiness engine specially handles tuple subclasses and __bool__. If line 497 selects between a depth tuple and an edge object, pruning the tuple-producing path removes exactly these three member diagnostics. There is no type-erasure signal, but disappearance of all outer-API checks is independently significant. Current Spack source was inspected only as a nonhistorical reference; the exact primer revision and call-site guard were not resolved, so the causal expression remains uncertain and this cannot be called a proven defect.

Uncertainty / next check: Inspect the recorded traversal return annotation and line-497 guard. Control `tuple[int, Edge] | Edge` with plain bool must retain member errors; only a Literal guard that proves the tuple arm impossible should remove them.

  • Exact PR head can remove a ternary-produced union arm based on truthiness.:
    evaluator: TypeEvaluator,
    node: TernaryNode,
    flags: EvalFlags,
    inferenceContext: InferenceContext | undefined
    ): TypeResult {
    if ((flags & EvalFlags.TypeExpression) !== 0) {
    evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.ternaryNotAllowed(), node);
    return { type: UnknownType.create() };
    }
    const testTypeResult = evaluator.getTypeOfExpression(node.d.testExpr);
    const typesToCombine: Type[] = [];
    let isIncomplete = false;
    let typeErrors = false;
    let constExprValue: boolean | undefined;
    if (!testTypeResult.isIncomplete) {
    if (!evaluator.canBeFalsy(testTypeResult.type)) {
    constExprValue = true;
    } else if (!evaluator.canBeTruthy(testTypeResult.type)) {
    constExprValue = false;
    }
    }
    if (constExprValue !== false && evaluator.isNodeReachable(node.d.ifExpr)) {
    const ifType = evaluator.getTypeOfExpression(node.d.ifExpr, flags, inferenceContext);
    typesToCombine.push(ifType.type);
    if (ifType.isIncomplete) {
    isIncomplete = true;
    }
  • Exact PR head changes tuple/__bool__/__len__ truthiness decisions that feed branch selection.:
    // Sentinels are always truthy.
    if (isSentinelLiteral(type)) {
    return false;
    }
    // Handle tuples specially.
    if (isTupleClass(type) && type.priv.tupleTypeArgs) {
    return isUnboundedTupleClass(type) || type.priv.tupleTypeArgs.length === 0;
    }
    // Handle subclasses of tuple, such as NamedTuple, that don't define __bool__.
    const tupleBaseClass = type.shared.mro.find((mroClass) => !isClass(mroClass) || isTupleClass(mroClass));
    if (
    tupleBaseClass &&
    isClass(tupleBaseClass) &&
    tupleBaseClass.priv.tupleTypeArgs &&
    !lookUpObjectMember(type, '__bool__')
    ) {
    return isUnboundedTupleClass(tupleBaseClass) || tupleBaseClass.priv.tupleTypeArgs.length === 0;
    }
    // Handle TypedDicts specially. If one or more entries are required
    // or known to exist, we can say for sure that the type is not falsy.
    if (ClassType.isTypedDictClass(type)) {
    const tdEntries = getTypedDictMembersForClass(evaluatorInterface, type, /* allowNarrowed */ true);
    if (tdEntries) {
    for (const tdEntry of tdEntries.knownItems.values()) {
    if (tdEntry.isRequired || tdEntry.isProvided) {
    return false;
    }
    }
    }
    }
    // Check for bool, int, str and bytes literals that are never falsy.
    if (type.priv.literalValue !== undefined) {
    if (ClassType.isBuiltIn(type, ['bool', 'int', 'str', 'bytes'])) {
    return !type.priv.literalValue || type.priv.literalValue === BigInt(0);
    }
    if (type.priv.literalValue instanceof EnumLiteral) {
    // Does the Enum class forward the truthiness check to the
    // underlying member type?
    if (type.priv.literalValue.isReprEnum) {
    return canBeFalsy(type.priv.literalValue.itemType, recursionCount);
    }
    }
    }
    // If this is a protocol class, don't make any assumptions about the absence
    // of specific methods. These could be provided by a class that conforms
    // to the protocol.
    if (ClassType.isProtocolClass(type)) {
    return true;
    }
    const boolMethod = lookUpObjectMember(type, '__bool__');
    if (boolMethod) {
    const boolMethodType = getTypeOfMember(boolMethod);
    // If the __bool__ function unconditionally returns True, it can never be falsy.
    if (isFunction(boolMethodType) && boolMethodType.shared.declaredReturnType) {
    const returnType = boolMethodType.shared.declaredReturnType;
    if (
    isClassInstance(returnType) &&
    ClassType.isBuiltIn(returnType, 'bool') &&
    returnType.priv.literalValue === true
    ) {
    return false;
    }
    }
    return true;
    }
    // Truthiness falls back to __len__ only if __bool__ isn't defined.
    const lenMethod = lookUpObjectMember(type, '__len__');
    if (lenMethod) {
    return true;

alerta: Five None-safety checks disappear from one query-building region, consistent with a nullable branch being declared unreachable rather than the values being narrowed safely.

Regression warning signals require review, regardless of the AI assessment:

  • Type-checking diagnostics disappear without replacements at the same locations.

AI assessment: Possible regression (high confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At postgres/base.py:349 the baseline rejected `.attributes` on None; at lines 369, 379, 388, and 397 it rejected iterating None. These are distinct observed optional checks in a concentrated control-flow region.

After / PR evidence: All five diagnostics vanish with no replacement narrowing detail. The raw evidence does not show assignments or guards that exclude None, and no Alerta declaration change is part of this Pyright PR.

Why this matters: Downstream users can no longer rely on Pyright to catch member access or iteration when these database values are absent. This is a loss of None-safety checking even if tests happen not to exercise the runtime path.

Causal analysis:

The PR broadens static-condition handling: boolean expressions gain literal types, declared/Final references can mark branches unreachable, member-access conditions participate, and ternaries omit arms based on canBeFalsy/canBeTruthy. A condition surrounding this repeated postgres block can therefore eliminate the None-bearing path, removing exactly the optional-member/iterable errors. The clustered loss and explicit removed-check signal make a regression credible. Counterevidence is that the condition could be genuinely static in the configured environment, but the exact Alerta revision and guard were unavailable, so this was not proven. No type erasure was observed; the issue is suppressed analysis of an alternative.

Uncertainty / next check: Resolve the recorded file and inspect the shared guard/assignment before lines 349-397. With a plain bool or Optional value, all five checks should remain; with an imported Final Literal condition, only the demonstrably unreachable side should be skipped.

  • Exact PR head resolves declared and Final condition references, including module members.:
    };
    }
    // Determines whether a condition's reference is a Final variable assigned a
    // value in its declaration or has a declared type, looking through imports.
    // Other types aren't inferred because that would be too expensive.
    function getConditionReferenceDeclKind(
    reference: NameNode | MemberAccessNode
    ): ConditionReferenceDeclKind | undefined {
    let symbol: Symbol | undefined;
    if (reference.nodeType === ParseNodeType.Name) {
    symbol = evaluator.lookUpSymbolRecursive(reference, reference.d.value, /* honorCodeFlow */ false)?.symbol;
    } else {
    const baseExpr = reference.d.leftExpr;
    if (baseExpr.nodeType !== ParseNodeType.Name) {
    return undefined;
    }
    const baseType = evaluator.getTypeOfExpression(baseExpr).type;
    if (isModule(baseType)) {
    symbol = ModuleType.getField(baseType, reference.d.member.d.value);
    }
    }
    if (!symbol) {
    return undefined;
    }
    const resolvedDecls = symbol
    .getDeclarations()
    .map((decl) => evaluator.resolveAliasDeclaration(decl, /* resolveLocalNames */ true));
    if (
    resolvedDecls.some(
    (decl) => decl?.type === DeclarationType.Variable && !!decl.isFinal && !!decl.inferredTypeSource
    )
    ) {
    return ConditionReferenceDeclKind.Final;
    }
    if (symbol.hasTypedDeclarations() || resolvedDecls.some((decl) => decl && hasTypeForDeclaration(decl))) {
    return ConditionReferenceDeclKind.Declared;
    }
  • Exact PR head uses those references to classify control-flow as unreachable.:
    ) {
    const conditionalFlowNode = curFlowNode as FlowCondition;
    if (conditionalFlowNode.reference) {
    const referenceDeclKind = getConditionReferenceDeclKind(conditionalFlowNode.reference);
    if (referenceDeclKind !== undefined) {
    let unreachability: Reachability | undefined;
    const typeNarrowingCallback = getTypeNarrowingCallback(
    evaluator,
    conditionalFlowNode.reference!,
    conditionalFlowNode.expression,
    !!(
    conditionalFlowNode.flags &
    (FlowFlags.TrueCondition | FlowFlags.TrueNeverCondition)
    ),
    nodeInfo
    );
    if (typeNarrowingCallback) {
    const refTypeInfo = evaluator.getTypeOfExpression(conditionalFlowNode.reference!);
    const narrowedTypeResult = applyTypeNarrowingCallback(
    typeNarrowingCallback,
    refTypeInfo.type
    );
    const narrowedType = narrowedTypeResult?.type ?? refTypeInfo.type;
    if (isNever(narrowedType) && !refTypeInfo.isIncomplete) {
    // A Final with a literal type is treated like a
    // statically-evaluated condition.
    unreachability =
    referenceDeclKind === ConditionReferenceDeclKind.Final &&
    isClassInstance(refTypeInfo.type) &&
    isLiteralType(refTypeInfo.type)
    ? Reachability.UnreachableStaticCondition
    : Reachability.UnreachableByAnalysis;
    }
  • PR tests intentionally suppress errors in branches controlled by local, imported, aliased, and module-member Final static conditions.:
    IS_WINDOWS_LOCAL: Final = sys.platform == "win32"
    @final
    class Flags:
    IS_WINDOWS: Final = sys.platform == "win32"
    FLAGS: Final = Flags()
    def func1() -> int:
    if IS_WINDOWS_LOCAL:
    return ""
    return 1
    def func2() -> int:
    if IS_WINDOWS:
    return ""
    return 1
    def func3() -> int:
    if not IS_WINDOWS:
    return 1
    return ""
    def func4() -> int:
    if WIN:
    return ""
    return 1
    def func5() -> int:
    if IS_WINDOWS_LITERAL:
    return ""
    return 1
    def func6() -> int:
    if staticExpression3.IS_WINDOWS:
    return ""
    return 1
    def func7() -> int:
    if DYNAMIC:
    # This should generate an error.
    return ""
    return 1
    def func8() -> int:
    if PLAIN:
    # This should generate an error.
    return ""
    return 1
    def func9(flags: Flags) -> int:
    if flags.IS_WINDOWS:
    # This should generate an error.
    return ""
    return 1
    def func10(staticExpression3: Any) -> int:
    if staticExpression3.IS_WINDOWS:
    # This should generate an error.
    return ""
    return 1
    def func11() -> int:
    if isinstance(FLAGS, int):
    # This should generate an error.
    return ""
    return 1
    def func12(flags: Flags) -> int:
    from . import staticExpression3 as module
    if module.IS_WINDOWS:
    return ""
    module = flags
    return 1
    def func13(flags: Flags) -> int:
    from . import staticExpression3 as module
    module = flags
    if module.IS_WINDOWS:
    # This should generate an error.
    return ""
    return 1
Other project assessments

scikit-learn: The failing index operation remains checked, while Unknown is removed from both slice endpoints; this is a diagnostic-detail precision gain rather than lost validation.

AI assessment: Expected improvement (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At _least_angle.py:803:34 the baseline rejected the tuple-of-slices key, displaying endpoints as int | Unknown. The key itself was still known as a tuple and the __getitem__ argument error was present.

After / PR evidence: The same location and incompatibility remain, but both endpoints are int. No header is truly gained or lost here: the apparent replacement is a message rewrite at one operation with more precise inferred endpoint types.

Why this matters: Downstream users retain the invalid-key diagnostic and gain usable int endpoint information. They can rely less on Unknown masking subsequent integer operations; no supported outer API or check disappears in the recorded evidence.

Causal analysis:

The PR makes statically evaluable boolean expressions literal and uses canBeFalsy/canBeTruthy to select ternary arms. A slice bound produced conditionally can therefore retain only the int arm instead of int | Unknown. This matches the observed endpoint-only refinement while preserving the tuple-key mismatch. The exact scikit-learn checkout was not resolved, so the causal expression at line 803 was not pinned; attribution is nevertheless likely because the only change is precisely the type precision controlled by the PR's ternary path. There is no type-erasure, removed-check, or assertion signal for this project.

Uncertainty / next check: Confirm the recorded line's bounds arise from a ternary/static condition. Positive control: a Literal[True] condition yields int endpoints; negative control: plain bool preserves both arms. The invalid tuple key should be diagnosed in both cases.

  • Exact PR head implements one-arm ternary inference from type truthiness.:
    evaluator: TypeEvaluator,
    node: TernaryNode,
    flags: EvalFlags,
    inferenceContext: InferenceContext | undefined
    ): TypeResult {
    if ((flags & EvalFlags.TypeExpression) !== 0) {
    evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.ternaryNotAllowed(), node);
    return { type: UnknownType.create() };
    }
    const testTypeResult = evaluator.getTypeOfExpression(node.d.testExpr);
    const typesToCombine: Type[] = [];
    let isIncomplete = false;
    let typeErrors = false;
    let constExprValue: boolean | undefined;
    if (!testTypeResult.isIncomplete) {
    if (!evaluator.canBeFalsy(testTypeResult.type)) {
    constExprValue = true;
    } else if (!evaluator.canBeTruthy(testTypeResult.type)) {
    constExprValue = false;
    }
    }
    if (constExprValue !== false && evaluator.isNodeReachable(node.d.ifExpr)) {
    const ifType = evaluator.getTypeOfExpression(node.d.ifExpr, flags, inferenceContext);
    typesToCombine.push(ifType.type);
    if (ifType.isIncomplete) {
    isIncomplete = true;
    }
  • PR test records intentional removal of an impossible ternary literal and a more precise resulting container element type.:
    def conditional_control() -> None:
    value = (("a",),)[0][0]
    result = "b" if value else ""
    row = (result,)
    rows = [row]
    assert_type(rows, list[tuple[Literal["b"]]])
    rows.append(("",)) # This should generate an argument-type error.

jax: Five diagnostics are message rewrites: an int alternative is refined to Literal[1], while every iterable/tuple-assignment failure remains at the same location.

AI assessment: Expected improvement (high confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At bcoo.py:418, 1418, and 1534, the baseline diagnosed non-iterable `int` and tuple-target unions ending in `int`. These were observed diagnostics; no outer Array or tuple API was erased.

After / PR evidence: The same five locations and errors remain, but each affected `int` is now `Literal[1]`. The union's Array and tuple alternatives are unchanged, so this is added value precision rather than a new or removed check.

Why this matters: Users retain all invalid-iteration and tuple-unpacking checks and gain the exact sentinel value responsible. Supported operations are not lost: Literal[1] supports the same int operations while enabling stronger narrowing.

Causal analysis:

The PR assigns literal types to statically evaluated boolean expressions and changes truthiness-aware ternary inference. A sentinel expression that previously widened to int now remains Literal[1], which propagates into BCOO's shape/result unions. The diagnostic continuity is an important control: unlike projects with vanished headers, Pyright still rejects every invalid iterable/tuple target. The exact JAX revision was unavailable, but the identical locations and otherwise identical unions establish that this is a detail-only precision change, and the PR's literal-preservation tests directly support the attribution.

Uncertainty / next check: Confirm the source expression producing 1 at the recorded JAX commit. Positive control should reveal Literal[1] while retaining a non-iterable error; a dynamically computed int should remain int. No assertion-failure or type-erasure signal needs follow-up here.

  • Exact PR head converts recognized static boolean expressions to literal bool types.:
    validateTypeIsInstantiable(typeResult, flags, node);
    }
    // If this is a constant boolean expression, assign it a literal type.
    if (
    (node.nodeType === ParseNodeType.Name ||
    node.nodeType === ParseNodeType.MemberAccess ||
    node.nodeType === ParseNodeType.UnaryOperation ||
    node.nodeType === ParseNodeType.BinaryOperation) &&
    (flags & EvalFlags.TypeExpression) === 0 &&
    isClassInstance(typeResult.type) &&
    ClassType.isBuiltIn(typeResult.type, 'bool') &&
    (typeResult.type.priv.literalValue === undefined ||
    (node.nodeType === ParseNodeType.Name && node.d.value === 'TYPE_CHECKING')) &&
    areTypeCheckingNamesValid(node)
    ) {
    const fileInfo = nodeInfo.getFileInfo(node);
    const constExprValue = evaluateStaticBoolExpression(
    node,
    fileInfo.executionEnvironment,
    fileInfo.definedConstants
    );
    if (constExprValue !== undefined) {
    typeResult = { ...typeResult, type: ClassType.cloneWithLiteral(typeResult.type, constExprValue) };
    }
    }
    // If this is a PEP 695 type alias, remove the special form so the type
    // printer prints it as its aliased type rather than TypeAliasType.
  • Exact PR test expects a conditionally inferred literal container element to stay precise.:
    def conditional_control() -> None:
    value = (("a",),)[0][0]
    result = "b" if value else ""
    row = (result,)
    rows = [row]
    assert_type(rows, list[tuple[Literal["b"]]])
    rows.append(("",)) # This should generate an argument-type error.

Full evidence and limitations: download mypy-primer-analysis-report from this analysis run.
The original raw primer comment is unchanged. Treat uncertainty and possible regressions as requests for human review.

@github-actions

Copy link
Copy Markdown
Contributor

Compared candidate ab70a2a5068241b26dd3262a13eb3cd7c957396f against its first parent 2981f9f1ce41be5c15667da1f7a3cfda4f245089.

Release history charts were not rendered for this run. See the workflow run for details.

Type checker benchmark

🟢 No performance regressions detected.

Regression threshold: 20.0%
Statistic: median
Variance guard: >1.0s time and >100.0 MB memory

Package Checker Files checked Time Time delta Peak memory Memory delta Status
ansible pyright 583 16.625s -4.1% 1076.4 MB +0.3% 🟢 Pass
click pyright 17 3.171s +1.0% 360.0 MB +0.4% 🟢 Pass
homeassistant pyright 9850 110.168s +3.5% 5993.9 MB -0.3% 🟢 Pass
numpy pyright 356 41.158s +1.9% 1215.3 MB +4.0% 🟢 Pass
pandas pyright 1459 138.975s +0.7% 3494.1 MB +0.4% 🟢 Pass
pytest pyright 243 10.477s +4.9% 867.7 MB -0.1% 🟢 Pass
requests pyright 19 1.872s +0.8% 347.7 MB -0.9% 🟢 Pass
torch pyright 2400 149.715s +1.8% 4621.2 MB -2.4% 🟢 Pass
transformers pyright 2901 76.994s -2.7% 5278.9 MB +8.7% 🟢 Pass

Pyright stats

Package Parsed/bound Checked Find Read Tokenize Parse Imports Bind Check Cycles
ansible 988 583 0.033s 0.080s 0.310s 0.613s 0.193s 0.780s 13.800s 0.000s
click 111 17 0.000s 0.013s 0.113s 0.203s 0.033s 0.270s 2.197s 0.000s
homeassistant 11157 9850 0.430s 0.603s 2.123s 3.070s 1.550s 5.067s 94.860s 0.000s
numpy 606 356 0.010s 0.070s 0.363s 0.683s 0.270s 0.963s 38.150s 0.000s
pandas 1899 1459 0.070s 0.227s 1.247s 2.513s 0.283s 2.723s 130.330s 0.000s
pytest 545 243 0.013s 0.043s 0.277s 0.413s 0.090s 0.573s 8.673s 0.000s
requests 167 19 0.000s 0.010s 0.093s 0.167s 0.043s 0.200s 1.083s 0.000s
torch 3078 2400 0.177s 0.360s 2.150s 3.703s 0.580s 4.860s 137.293s 0.000s
transformers 3546 2901 0.090s 0.277s 1.503s 2.387s 0.720s 6.250s 66.820s 0.000s

@crypt0lith

crypt0lith commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

AFAICT, none of the possible regressions in #12057 (comment) are new behavior.

🤖 AI-assisted findings

alerta and spack are call-site return type inference. alerta's _updateone, _updateall and _deleteall return cursor.fetchone() if returning else None (or fetchall()), and every flagged call passes returning=True. spack's edge generators yield (edge.depth, edge.edge) if depth else edge.edge, and the test doesn't pass depth, which defaults to False. The base already decides an if statement on those parameters the same way.

dd-trace-py, pandera and sympy's tensor.py:2373 are the canBeFalsy gap from my previous comment. The conditions are EnvVariable[bool] (envier's Env.v returns it), DataType (an ABC) and Basic, none of which define __bool__ or __len__, so the base's if, and and or already treat them as always truthy. #12077 addresses that gap.

In apprise, AttachBase only ever assigns None to download_path, so its path property is None and os.path.getsize(self.path) if self.path else 0 evaluates to Literal[0]. The new override error checks AttachMemory.__len__ against that inferred return type. The base infers the same return type for if self.path:.

The rest of sympy depends on the order its files are checked in. Checking simplify.py, sqrtdenest.py, meijerint.py, single.py and test_exprtools.py alone gives identical diagnostics on the base and this PR at meijerint.py:1491-1493, single.py:2757, simplify.py:166-201 and sqrtdenest.py:303. In that run the base itself reports sqrtdenest's None operand at line 309, not 303. The additions in test_exprtools.py are true positives: _monotonic_sign returns None, and the base infers its return type as Unknown.

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 on the PR head: the Final-reachability work from #12002/#12016 carries over, the new getBoolArgValue enables @dataclass(frozen=FINAL), and the focused suites pass. One behavior change worth an explicit decision — module constants without Final now also control frozen=/kw_only=.

✅ Suites

typeEvaluator1/4/8 -t 'Dataclass|StaticExpression|Final|Reachability' → 45 passed on the PR head.

✅ Imported-Final reachability — carries over from #12016

Re-ran the import-shape probe (direct / as-renamed / comparison / repeated import) against this PR: all four prune correctly, main prunes none. The resolveAliasDeclaration(decl, resolveLocalNames=true) path at codeFlowEngine.ts:1418 is doing the work. The three must-still-analyze controls (DYNAMIC, ANNOTATED, PLAIN) hold as in #12016.

✅ The new capability — type-based frozen=/kw_only=

getBoolArgValue replaces the old AST-only evaluateStaticBoolExpression for dataclass bool args. It evaluates the argument's type and uses canBeFalsy/canBeTruthy:

Declaration @dataclass(frozen=…) then obj.x = 2 main PR
FREEZE: Final = True (imported) A accepted error ✓
DYN: bool = True (unknown) D accepted accepted ✓ (correctly falls back)
NOT_FINAL = True (plain module constant) C accepted error ⚠️

The first two are exactly right. The fallback for a non-literal bool is sound: both canBeFalsy and canBeTruthy return true → undefined → default behaviour.

⚠️ Behavior change to confirm: implicit-Final module constants now count

Row 3 is the one to make a deliberate call on. NOT_FINAL = True has no Final, but Pyright already types it as Literal[True] on main (confirmed with reveal_type) — module-level constants are implicitly Final. So once the check is type-based, @dataclass(frozen=NOT_FINAL) freezes, where on main only a literal True did.

This is consistent with how Pyright already treats such constants everywhere else, and I'd argue it's an improvement (a CONFIG_FROZEN = True in a config module is a common pattern). But it is a user-visible change beyond the description's framing ("narrow bare Final"), and it will surface as new reportAttributeAccessIssue errors on code that previously type-checked. Two suggestions:

  1. Mention it in the PR description and the changelog entry explicitly, so it's not discovered as a surprise.
  2. Decide whether getBoolArgValue should require Final (or an explicitly-literal type) rather than accepting any bool-typed expression whose truthiness is decidable. Requiring Literal[True]/Literal[False] and a Final/constant declaration would keep the implicit-Final behaviour opt-in by annotation. Either is defensible — it just needs to be chosen.

📝 Minor

The refactor in dataClasses.ts (7 inline evaluateStaticBoolExpression calls → getBoolArgValue) drops the nodeInfo parameter from several functions, which is a nice simplification. The removed evaluateStaticBoolExpression import is no longer referenced — confirmed clean.

canBeFalsy decides a tuple subclass from its tuple length without
looking up __bool__ or __len__, so a non-empty subclass whose __bool__
or __len__ can return a falsy value is treated as always truthy. Use
the tuple length only when the class has no __bool__ and its __len__ is
tuple's, and look up both methods on the class only, as Python does.

Fixes microsoft#12074
@crypt0lith
crypt0lith force-pushed the fix/reachability-final-ref branch from 7a48423 to 62d3f3a Compare December 4, 2026 08:35
@crypt0lith

Copy link
Copy Markdown
Contributor Author

The reportReturnType finding from the QA bot run (head: 7a48423) is fixed in 2211e27. Main's and/or already got this case wrong: on pyright 1.1.414, Zero((1,)) or a is Zero. The tuple length is now used only when the class has no __bool__ and its __len__ is tuple.__len__, so a if Zero((1,)) else b is int | str again.

62d3f3a removes the __len__ that pyright synthesizes for namedtuple classes. A namedtuple class doesn't define __len__: collections.namedtuple creates it with type(typename, (tuple,), class_namespace), and the namespace has no __len__ (collections/__init__.py:497-515), so it uses tuple's. The synthesized __len__ came in with 1d91744, alongside synthesized keys and items, which 7194375 removed as a bug. With it in place, canBeFalsy could tell a namedtuple's length from an override only by checking for a synthesized method.

The synthesized __init__ stays, although namedtuple classes have no __init__ at runtime either. typing.NamedTuple is a function that delegates to collections.namedtuple (typing.py:3027). Subclassing it goes through NamedTupleMeta: NamedTuple.__mro_entries__ returns (_NamedTuple,) (typing.py:3093-3099), and the metaclass replaces it with tuple in the bases and builds the class with collections.namedtuple (typing.py:2960, typing.py:2994-2996). typeshed declares NamedTuple as a class whose __init__ overloads take the functional form's typename and fields, and that class is in the MRO of every namedtuple class in pyright. The synthesized __init__ hides those overloads; without it, constructing a namedtuple is checked against them.

The UserPlatform finding is still #12033 and fixed in #11929.

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

3 participants