Skip to content

Fix IntFlag bitwise narrowing with localized reflected-operator priority - #11977

Merged
Rich Chiodo (rchiodo) merged 4 commits into
microsoft:mainfrom
rchiodo:rchiodo-alternative-intflag-fix
Nov 9, 2026
Merged

Rich Chiodo (rchiodo) merged 4 commits into
microsoft:mainfrom
rchiodo:rchiodo-alternative-intflag-fix

Conversation

@rchiodo

Copy link
Copy Markdown
Collaborator

Summary

Fixes #11515.

This is an alternative approach to #11662 for IntFlag bitwise narrowing and reflected-operator priority. It fixes int() & Flags.A, int() | Flags.A, and int() ^ Flags.A revealing int instead of Flags.

The change is localized to arithmetic dispatch in operations.ts: try the reflected method first when the right operand is a declared strict subclass with a different reflected implementation. Otherwise retain the existing forward/reflected path.

It does not change disjoint-type narrowing or globally remove NotImplemented from operator results. Decline handling is limited to newly prioritized calls with explicit return contracts; inferred sentinel results retain legacy fallback behavior.

Coverage

Adds regression coverage for IntFlag operations in both directions, augmented assignment, ordinary integers and direct dunder calls, reflected overrides, inherited and aliased methods, explicit and inferred declines, partial-success fallback, generic precision, and synthetic narrowing intersections.

The new sample failed 13 revealed-type assertions before the production change.

Validation

  • All nine evaluator/checker suites: 1,496 tests passed against the final candidate.
  • TypeScript build, changed-file ESLint/Prettier, and git diff --check passed.
  • Frozen native mypy_primer corpus: 151 valid baseline/candidate pairs, 148 unchanged projects, three changed projects, no setup/checker failures. Fresh baseline output and commands matched the original baseline for all 151 projects. Dependency freezes and before/after source state were preserved. At most two checker processes ran concurrently.
  • The three full-corpus diffs exactly match the earlier bounded comparison:
    • Home Assistant: five IntFlag-related errors removed.
    • pandas-stubs: two unnecessary-ignore errors because existing Timedelta type assertions now succeed.
    • SymPy: net 25 additional diagnostics, not 25 newly rejected sites. One new Number-dictionary assignment diagnostic, 26 extra numeric alternatives at four already-failing sites, and two removed Quaternion return errors.

The SymPy widening follows reflected dispatch. A runtime probe at the exact Add.flatten assignment confirms Number operands can store a non-Number Add coefficient with evaluation disabled, including through Add(..., evaluate=True). Keeping an unconditional Number result would hide a possible runtime result. Ordinary evaluated numeric paths can nevertheless be more precise than the inferred reflected-return union.

Boundaries

This conservatively leaves declaration-free dynamic/synthetic classes, metaclass operands, callable descriptors, and distinct factory closures sharing declarations on the legacy path. Inferred NotImplemented precision issues are not addressed. No clean performance comparison has been performed.

Validated base: b57fefae2650597bd1a0f7fb3ce821015c25d317, including the receiver-binding fix in #11953.

Use a localized reflected-first path for distinct right-subclass implementations while preserving legacy narrowing and inferred-sentinel behavior.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@heejaechang

Heejae Chang (heejaechang) commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — c23c6247 — verdict: red

Automated CLI checks compared this change with its base revision.
19 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:

control.py

from enum import IntFlag
from typing import assert_type
reveal_type(0)
class Bits(IntFlag):
    A = 1
    B = 2

def check(n: int):
    assert_type(Bits.A | n, Bits)
    assert_type(Bits.A.__or__(n), Bits)
    Bits.A.__or__(n).name

explicit_keep.py

from enum import KEEP, IntFlag
from typing import Callable, assert_type
reveal_type(0)
Bits = IntFlag("Bits", ("A", "B"), boundary=KEEP)
def check(n: int):
    assert_type(Bits.A | n, Bits)
    assert_type(Bits.A & n, Bits)
    assert_type(Bits.A ^ n, Bits)
    op = Bits.A.__or__
    op(n).name
    values: list[Bits] = [op(n)]
    values[0].name
def callback() -> Callable[[int], Bits]:
    return Bits.A.__xor__

main.py

from enum import IntFlag
reveal_type(0)
Bits = IntFlag("Bits", {"A": 1})

def name(n: int) -> str | None:
    return Bits.A.__or__(n).name

pyrightconfig.json

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

runtime.py

import json
import sys
from enum import IntFlag

Bits = IntFlag("Bits", {"A": 1})
ListBits = IntFlag("ListBits", ["A", "B"])
PairBits = IntFlag("PairBits", [("A", 1), ("B", 2)])
print(sys.version, flush=True)
for cls in (Bits, ListBits, PairBits):
    for method in ("__or__", "__xor__", "__and__", "__ror__", "__rxor__", "__rand__"):
        result = getattr(cls.A, method)(8)
        assert type(result) is cls
        result.name
        print(json.dumps({"enum": cls.__name__, "method": method,
                          "result_type": type(result).__name__, "value": int(result)}), flush=True)
print("functional KEEP operations preserve enum membership", flush=True)

types.py

from enum import IntFlag
from typing import Callable, assert_type
reveal_type(0)
Bits = IntFlag("Bits", ["A", "B"])
Pairs = IntFlag("Pairs", [("A", 1), ("B", 2)])

def check(n: int):
    assert_type(Bits.A | n, Bits)
    assert_type(Bits.A ^ n, Bits)
    assert_type(Bits.A & n, Bits)
    assert_type(Bits.A.__ror__(n), Bits)
    assert_type(Bits.__xor__(Bits.A, n), Bits)
    assert_type(IntFlag.__and__(Bits.A, n), Bits)
    assert_type(Pairs.A.__or__(n), Pairs)

def callback() -> Callable[[int], Bits]:
    return Bits.A.__or__

From that directory, run each built Pyright revision:

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

Base 500dd234ac78bb9bf314590591a7c0b2fdf99cef

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"IntFlag\"",
      "range": {
        "start": [
          12,
          16
        ],
        "end": [
          12,
          42
        ]
      }
    }
  ]
}

PR c23c624754b48eb09239391e33bb61b280419a1d

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          9,
          10
        ],
        "end": [
          9,
          14
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Overload[(other: Literal[Bits.A, 0]) -> Bits, (other: int) -> int]\" is not assignable to return type \"(int) -> Bits\"\n  No overloaded function matches type \"(int) -> Bits\"",
      "range": {
        "start": [
          13,
          11
        ],
        "end": [
          13,
          25
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "error",
      "rule": "reportAssignmentType",
      "message": "Type \"list[int]\" is not assignable to declared type \"list[Bits]\"\n  \"int\" is not assignable to \"Bits\"",
      "range": {
        "start": [
          10,
          26
        ],
        "end": [
          10,
          31
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          5,
          16
        ],
        "end": [
          5,
          26
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          6,
          16
        ],
        "end": [
          6,
          26
        ]
      }
    },
    {
      "file": "explicit_keep.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          7,
          16
        ],
        "end": [
          7,
          26
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          5,
          28
        ],
        "end": [
          5,
          32
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Overload[(other: Literal[Bits.A, 0]) -> Bits, (other: int) -> int]\" is not assignable to return type \"(int) -> Bits\"\n  No overloaded function matches type \"(int) -> Bits\"",
      "range": {
        "start": [
          16,
          11
        ],
        "end": [
          16,
          24
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          33
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          11,
          16
        ],
        "end": [
          11,
          39
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          12,
          16
        ],
        "end": [
          12,
          42
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          7,
          16
        ],
        "end": [
          7,
          26
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          8,
          16
        ],
        "end": [
          8,
          26
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          9,
          16
        ],
        "end": [
          9,
          26
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Pairs\" but received \"int\"",
      "range": {
        "start": [
          13,
          16
        ],
        "end": [
          13,
          33
        ]
      }
    }
  ]
}

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

from enum import EJECT, IntFlag
from typing import assert_type
reveal_type(0)
class Bits(IntFlag, boundary=EJECT):
    A = -1

def check():
    assert_type(Bits.A | 1, Bits)
    assert_type(Bits.A ^ 0, Bits)
    (Bits.A | 1).name

main.py

from enum import EJECT, IntFlag
reveal_type(0)
class Bits(IntFlag, boundary=EJECT):
    A = -1

def name() -> str | None:
    return (Bits.A ^ Bits.A).name

other_member.py

from enum import EJECT, IntFlag
from typing import Callable, Literal, assert_type
reveal_type(0)
class Bits(IntFlag, boundary=EJECT):
    A = -1
    B = -2
    ALIAS = B
def check():
    assert_type(Bits.A & Bits.B, Bits)
    (Bits.A & Bits.B).name
    assert_type(Bits.B | Bits.A, Bits)
    (Bits.B | Bits.A).name
    assert_type(Bits.A.__and__(Bits.ALIAS), Bits)
    Bits.__and__(Bits.A, Bits.B).name
def callback() -> Callable[[Literal[Bits.B]], Bits]:
    return Bits.A.__and__

pyrightconfig.json

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

runtime.py

import json
import sys
from enum import EJECT, IntFlag

class Bits(IntFlag, boundary=EJECT):
    A = -1

print(sys.version, flush=True)
for result in (Bits.A ^ Bits.A, Bits.A.__xor__(Bits.A), Bits.__xor__(Bits.A, Bits.A),
               IntFlag.__xor__(Bits.A, Bits.A), -1 ^ Bits.A):
    assert type(result) is Bits
    assert result == 0
    result.name
    print(json.dumps({"result_type": type(result).__name__, "value": int(result), "name": result.name}), flush=True)
assert type(Bits.A ^ 1) is int
print("self XOR retains enum membership; XOR with 1 ejects", flush=True)

types.py

from enum import EJECT, IntFlag
from typing import Callable, Literal, assert_type
reveal_type(0)
class Bits(IntFlag, boundary=EJECT):
    A = -1

def check():
    assert_type(Bits.A ^ Bits.A, Bits)
    assert_type(Bits.A.__xor__(Bits.A), Bits)
    assert_type(Bits.__xor__(Bits.A, Bits.A), Bits)
    assert_type(IntFlag.__xor__(Bits.A, Bits.A), Bits)
    assert_type(-1 ^ Bits.A, Bits)
    packed: tuple[Literal[Bits.A], Literal[Bits.A]] = (Bits.A, Bits.A)
    assert_type(IntFlag.__xor__(*packed), Bits)

def callback() -> Callable[[Literal[Bits.A]], Bits]:
    return Bits.A.__xor__

From that directory, run each built Pyright revision:

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

Base 500dd234ac78bb9bf314590591a7c0b2fdf99cef

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"IntFlag\"",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          47
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"IntFlag\"",
      "range": {
        "start": [
          13,
          16
        ],
        "end": [
          13,
          40
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          11,
          16
        ],
        "end": [
          11,
          27
        ]
      }
    }
  ]
}

PR c23c624754b48eb09239391e33bb61b280419a1d

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          6,
          29
        ],
        "end": [
          6,
          33
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          11,
          22
        ],
        "end": [
          11,
          26
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          13,
          33
        ],
        "end": [
          13,
          37
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          9,
          22
        ],
        "end": [
          9,
          26
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Overload[(other: Literal[0]) -> Bits, (other: int) -> int]\" is not assignable to return type \"(Literal[Bits.B]) -> Bits\"\n  No overloaded function matches type \"(Literal[Bits.B]) -> Bits\"",
      "range": {
        "start": [
          15,
          11
        ],
        "end": [
          15,
          25
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          31
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          12,
          16
        ],
        "end": [
          12,
          42
        ]
      }
    },
    {
      "file": "other_member.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          8,
          16
        ],
        "end": [
          8,
          31
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportReturnType",
      "message": "Type \"Overload[(other: Literal[0]) -> Bits, (other: int) -> int]\" is not assignable to return type \"(Literal[Bits.A]) -> Bits\"\n  No overloaded function matches type \"(Literal[Bits.A]) -> Bits\"",
      "range": {
        "start": [
          16,
          11
        ],
        "end": [
          16,
          25
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          10,
          16
        ],
        "end": [
          10,
          47
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          11,
          16
        ],
        "end": [
          11,
          27
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          13,
          16
        ],
        "end": [
          13,
          40
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          7,
          16
        ],
        "end": [
          7,
          31
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          8,
          16
        ],
        "end": [
          8,
          38
        ]
      }
    },
    {
      "file": "types.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          9,
          16
        ],
        "end": [
          9,
          44
        ]
      }
    }
  ]
}

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

from enum import EJECT, IntFlag
from typing import Callable, Literal, ParamSpec, TypeVar, assert_type
reveal_type(0)
P = ParamSpec("P")
R = TypeVar("R")
def identity(fn: Callable[P, R]) -> Callable[P, R]:
    return fn
class Bits(IntFlag, boundary=EJECT):
    A = 1
    B = 4
def direct(bits: Bits):
    callback: Callable[[Literal[4]], Bits] = bits.__or__
    assert_type(callback(4), Bits)
    callback(4).name
def declared(callback: Callable[[Literal[4]], Bits]):
    assert_type(identity(callback)(4), Bits)
    identity(callback)(4).name

main.py

from enum import EJECT, IntFlag
from typing import Callable, Literal, ParamSpec, TypeVar
reveal_type(0)
P = ParamSpec("P")
R = TypeVar("R")
def identity(fn: Callable[P, R]) -> Callable[P, R]:
    return fn
class Bits(IntFlag, boundary=EJECT):
    A = 1
    B = 4
def name(bits: Bits) -> str | None:
    callback: Callable[[Literal[4]], Bits] = bits.__or__
    return identity(callback)(4).name

pyrightconfig.json

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

runtime.py

import json
import sys
from enum import EJECT, IntFlag
from typing import Callable, Literal, ParamSpec, TypeVar

P = ParamSpec("P")
R = TypeVar("R")
def identity(fn: Callable[P, R]) -> Callable[P, R]:
    return fn
class Bits(IntFlag, boundary=EJECT):
    A = 1
    B = 4

print(sys.version, flush=True)
for method in ("__or__", "__xor__", "__and__"):
    callback: Callable[[Literal[4]], Bits] = getattr(Bits.A, method)
    result = identity(callback)(4)
    assert type(result) is Bits
    result.name
    print(json.dumps({"method": method, "type": type(result).__name__,
                      "value": int(result), "name": result.name}), flush=True)
print("ParamSpec identity preserves valid literal-4 flag callbacks", flush=True)

variants.py

from enum import EJECT, IntFlag
from typing import Callable, Literal, ParamSpec, TypeVar, assert_type
reveal_type(0)
P = ParamSpec("P")
R = TypeVar("R")
def identity(fn: Callable[P, R]) -> Callable[P, R]:
    return fn
class Bits(IntFlag, boundary=EJECT):
    A = 1
    B = 4
def xor(bits: Bits):
    callback: Callable[[Literal[4]], Bits] = bits.__xor__
    assert_type(identity(callback)(4), Bits)
    identity(callback)(4).name
def and_(bits: Bits):
    callback: Callable[[Literal[4]], Bits] = bits.__and__
    assert_type(identity(callback)(4), Bits)
    identity(callback)(4).name
def zero(bits: Bits):
    callback: Callable[[Literal[0]], Bits] = bits.__or__
    assert_type(identity(callback)(0), Bits)

From that directory, run each built Pyright revision:

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

Base 500dd234ac78bb9bf314590591a7c0b2fdf99cef

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

PR c23c624754b48eb09239391e33bb61b280419a1d

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "control.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Literal[4]\" cannot be assigned to parameter \"other\" of type \"Bits | Literal[0]\"\n  Type \"Literal[4]\" is not assignable to type \"Bits | Literal[0]\"\n    \"Literal[4]\" is not assignable to \"Bits\"\n    \"Literal[4]\" is not assignable to type \"Literal[0]\"",
      "range": {
        "start": [
          12,
          30
        ],
        "end": [
          12,
          31
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          12,
          33
        ],
        "end": [
          12,
          37
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Literal[4]\" cannot be assigned to parameter \"other\" of type \"Bits | Literal[0]\"\n  Type \"Literal[4]\" is not assignable to type \"Bits | Literal[0]\"\n    \"Literal[4]\" is not assignable to \"Bits\"\n    \"Literal[4]\" is not assignable to type \"Literal[0]\"",
      "range": {
        "start": [
          12,
          35
        ],
        "end": [
          12,
          36
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Literal[4]\" cannot be assigned to parameter \"other\" of type \"Bits | Literal[0]\"\n  Type \"Literal[4]\" is not assignable to type \"Bits | Literal[0]\"\n    \"Literal[4]\" is not assignable to \"Bits\"\n    \"Literal[4]\" is not assignable to type \"Literal[0]\"",
      "range": {
        "start": [
          13,
          23
        ],
        "end": [
          13,
          24
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Literal[4]\" cannot be assigned to parameter \"other\" of type \"Bits | Literal[0]\"\n  Type \"Literal[4]\" is not assignable to type \"Bits | Literal[0]\"\n    \"Literal[4]\" is not assignable to \"Bits\"\n    \"Literal[4]\" is not assignable to type \"Literal[0]\"",
      "range": {
        "start": [
          16,
          35
        ],
        "end": [
          16,
          36
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Literal[4]\" cannot be assigned to parameter \"other\" of type \"Bits | Literal[0]\"\n  Type \"Literal[4]\" is not assignable to type \"Bits | Literal[0]\"\n    \"Literal[4]\" is not assignable to \"Bits\"\n    \"Literal[4]\" is not assignable to type \"Literal[0]\"",
      "range": {
        "start": [
          17,
          23
        ],
        "end": [
          17,
          24
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          13,
          26
        ],
        "end": [
          13,
          30
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot access attribute \"name\" for class \"int\"\n  Attribute \"name\" is unknown",
      "range": {
        "start": [
          17,
          26
        ],
        "end": [
          17,
          30
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          2,
          12
        ],
        "end": [
          2,
          13
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          12,
          16
        ],
        "end": [
          12,
          37
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          16,
          16
        ],
        "end": [
          16,
          37
        ]
      }
    },
    {
      "file": "variants.py",
      "severity": "error",
      "rule": "reportAssertTypeFailure",
      "message": "\"assert_type\" mismatch: expected \"Bits\" but received \"int\"",
      "range": {
        "start": [
          20,
          16
        ],
        "end": [
          20,
          37
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

@github-actions

This comment has been minimized.

Retain nonreturning forward results and refine EJECT bitwise returns across direct calls, callbacks, and packed arguments. Guard numeric value proofs against custom operations and storage, with focused regression coverage.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@rchiodo

Copy link
Copy Markdown
Collaborator Author

I investigated the SymPy primer diff, and I think we should accept these differences rather than add a dispatch exception to preserve the old results. The change follows Python's runtime precedence for a distinct reflected implementation on a strict right subclass. The results include an attainable widening at the newly failing site, better Quaternion precision, and additional diagnostics at expressions that already failed.

The net +25 errors are not 25 newly rejected expressions. Grouping the complete local paired diagnostics by file, line, column, and severity gives:

Change Explanation
+1 new site sympy/core/add.py:352: terms[s] += c updates a Number-valued dictionary, but the result now includes Expr.
+21 diagnostic alternatives Seven additional numeric alternatives at each of three unpack sites: integrals.py:1199, integrals.py:1311, and test_risch.py:799. These expressions already failed for Expr and None.
+5 diagnostic alternatives The .q access at test_wester.py:403 already failed for Expr; it now reports additional numeric alternatives.
-2 sites Quaternion return errors at quaternion.py:726 and :1708 disappear. A paired actual-import probe changes Expr * Quaternion from Expr to Quaternion, matching runtime.

That accounts for +1 +21 +5 -2 = +25. There are 20 rewritten existing diagnostic groups overall. In particular, the advisory's unpacking and .q entries should not be read as newly failing locations in this frozen comparison.

The new dictionary diagnostic was checked at the exact caller. With actual SymPy imports, Number + Integer widens beyond Number because the reflected RHS implementation now gets priority. Explicit number.__add__(integer), Number + Number, and Integer + Integer retain their baseline types.

I executed [Mul(Float(1.5), x, evaluate=False), x] through the coefficient accumulation and recorded the values at add.py:352. The operands are actual Float and One objects, both instances of Number. Ordinary evaluation stores a Float. Under global evaluate(False), both Add(*seq, evaluate=True) and public Add.flatten(list(seq)) reach that same assignment and store a non-Number Add. Even explicit evaluate=True does not universally establish the dictionary's Number invariant.

That's why I'm accepting the widening: restoring Number-only behavior would hide an attainable result and undo runtime-correct dispatch. The ordinary evaluated path may still be broader than ideal because the checker doesn't encode all of SymPy's evaluation-state correlations. This is not a claim that every diagnostic is a runtime bug, or that every transitive union alternative was independently traced.

For reproducibility, the local frozen comparison used PR head 13ff3b36b6878fda226bde94374006fec302da4a against b57fefae2650597bd1a0f7fb3ce821015c25d317, with SymPy pinned to fd810f89b86e6e8efa2e9cef034a4391aadbf026. All 151 project pairs were valid; 148 were unchanged, with only core, pandas-stubs, and SymPy differing. The exact-final QA revision reproduced the same three project diffs. These are local frozen-run results, separate from hosted CI's synthetic merge artifacts, not a universal regression-safety claim.

@heejaechang

Copy link
Copy Markdown
Collaborator

The new flag mask proof can hide a real .name error in reverse OR/XOR. There is also a separate conservative precision loss for a negative member. Both are reproduced on the reviewed head, compared with the pre-PR baseline.

Custom _value_ interception can erase a real consumer error

hasStandardFlagConstruction checks custom construction and _value_ declarations, but not a custom __getattribute__ that changes the value used by Flag.__or__:

from enum import EJECT, IntFlag

class F(IntFlag, boundary=EJECT):
    A = 1
    def __getattribute__(self, name: str) -> object:
        return 8 if name == "_value_" else super().__getattribute__(name)

reveal_type(1 | F.A)
print((1 | F.A).name)

Executed with Python target 3.13, basic checking, and each revision's identical typeshed:

Observation Baseline PR head
Inferred 1 | F.A int F
.name access reportAttributeAccessIssue No error

CPython 3.13.17 evaluates the operation to int(9) and the consumer raises AttributeError: 'int' object has no attribute 'name'. There are no unrelated setup diagnostics in this reproduction.

The class-body mask is 1, but the runtime operation uses _value_ == 8. The new reflected priority exposes this to reverse OR/XOR, while the mask proof still treats construction/storage as standard. This is a newly lost diagnostic, not merely a pre-existing direct-order issue.

The same diagnostic loss is confirmed with an inherited __getattribute__ and reverse XOR. Direct/bound calls and a flag-returning callback are also unsound with this storage pattern, but those consumer failures were already accepted by the baseline. Ordinary A=1 with OR1 remains a valid positive control; ordinary OR8 is still rejected at the PR head.

Could the storage guard conservatively account for custom _value_ access, including inherited __getattribute__, before using the class-body mask? Please add both the reverse-order consumer regression and the ordinary-storage control. The relevant guard is enums.ts:787–790.

Safe negative-member OR loses precision

There is also a separate conservative precision tradeoff, not a soundness defect:

from enum import EJECT, IntFlag

class Negative(IntFlag, boundary=EJECT):
    A = -1

reveal_type(Negative.A | 1)

def valid() -> Negative:
    return Negative.A | 1

The baseline infers Negative and accepts the return. The PR infers int and adds reportReturnType. CPython 3.13.17 returns the existing Negative.A object: -1 | 1 == -1. This uses a known member, not an arbitrary int operand or custom construction.

The bound Negative.A.__or__(1) form has the same new rejection. The unbound form was already rejected by the baseline with the less specific IntFlag return, so I am not counting it as a new regression. As negative controls, Negative.A ^ 1 really does eject to int(-2) and is correctly rejected by the PR, while XOR0 remains accepted.

getNonNegativeFlagMask drops the proof whenever a member is negative, even when the exact operation returns an existing member. Could the known-literal case retain its flag type, or could this newly rejected valid case be explicitly justified as an accepted limitation? This should not be addressed by making all negative-member operations return Self, because the XOR1 neighbor must remain an error.

Both revision builds and all 1,502 head evaluator/checker tests pass locally. The examples above are additional executed differential probes, not failures claimed from that existing suite.

Classification B (Pyright inference limitations): invalidate flag value proofs when custom attribute access can change _value_, and preserve exact literal operations that reuse the same known enum member. Keep builtin integer-payload operand proofs independent of attribute access, with focused operator, callback and packed-call coverage.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@rchiodo

Copy link
Copy Markdown
Collaborator Author

Heejae Chang (@heejaechang) Fixed both in 6889680.

The storage guard now checks for custom __getattribute__, including inherited overrides, before trusting mask, zero, or existing-member proofs. This restores the reverse OR/XOR .name errors and applies consistently to direct calls and callbacks. Ordinary storage remains precise. Custom access is deliberately conservative: even if a particular intercepted operation happens to return a flag, its class-body mask no longer establishes that guarantee.

For an exact known member and literal numeric or same-enum operand, we now calculate the bitwise result and preserve the flag type when it equals that member's value. This matches CPython's existing-member reuse before EJECT: Negative.A | 1 remains Negative, including bound/packed/callback forms, while Negative.A ^ 1 remains int and its unsafe consumers stay errors. This is not a blanket Self result for negative arithmetic.

Added failing-before regression coverage for both concerns and ordinary-storage controls. All 1,503 evaluator/checker tests, build, lint, and formatting pass; runtime probes used Python 3.13.13 with a 3.13/basic checking target. Previous packed-call, callback, and Never witnesses remain passing.

The earlier full 151-project primer results do not validate this new commit; I haven't rerun that corpus locally for this bounded follow-up.

Integrate upstream evaluator modularization, moving callable refinement and private argument metadata to their new owners while preserving validated IntFlag behavior and packed-argument correlation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

github-actions Bot commented Nov 7, 2026

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/algebras/quaternion.py:726:16 - error: Type "Expr" is not assignable to return type "Quaternion"
-     "Expr" is not assignable to "Quaternion" (reportReturnType)
-   .../projects/sympy/sympy/algebras/quaternion.py:1708:16 - error: Type "Expr" is not assignable to return type "Quaternion"
-     "Expr" is not assignable to "Quaternion" (reportReturnType)
+   .../projects/sympy/sympy/core/add.py:352:17 - error: Argument of type "Number | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Expr" cannot be assigned to parameter "value" of type "Number" in function "__setitem__"
+     Type "Number | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Expr" is not assignable to type "Number"
+       "Expr" is not assignable to "Number" (reportArgumentType)
-     Return type mismatch: base method returns type "tuple[Expr, Expr]", override returns type "tuple[Mul, Zero] | tuple[Zero, Expr] | tuple[Expr, Expr] | tuple[Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType, Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType] | tuple[Expr | Unknown | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number, Expr | Unknown | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number] | None"
+     Return type mismatch: base method returns type "tuple[Expr, Expr]", override returns type "tuple[Mul, Zero] | tuple[Zero, Expr] | tuple[Expr, Expr] | tuple[Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType, Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType] | tuple[Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Unknown, Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Unknown | Infinity | NegativeInfinity | Float | Number] | None"
-       Type "tuple[Mul, Zero] | tuple[Zero, Expr] | tuple[Expr, Expr] | tuple[Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType, Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType] | tuple[Expr | Unknown | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number, Expr | Unknown | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number] | None" is not assignable to type "tuple[Expr, Expr]"
+       Type "tuple[Mul, Zero] | tuple[Zero, Expr] | tuple[Expr, Expr] | tuple[Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType, Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType] | tuple[Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Unknown, Expr | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Unknown | Infinity | NegativeInfinity | Float | Number] | None" is not assignable to type "tuple[Expr, Expr]"
-   .../projects/sympy/sympy/core/numbers.py:1089:24 - error: Operator "*" not supported for types "Expr" and "Float* | ComplexInfinity | Zero | NaN | Infinity | NegativeInfinity | Float | Expr | Unknown | One | NegativeOne | Integer | Rational | Number | NotImplementedType | Literal[0] | None"
+   .../projects/sympy/sympy/core/numbers.py:1089:24 - error: Operator "*" not supported for types "Expr" and "Float* | ComplexInfinity | Zero | NaN | Infinity | NegativeInfinity | Float | One | NegativeOne | Integer | Rational | Expr | Unknown | Number | NotImplementedType | Literal[0] | None"
-     Return type mismatch: base method returns type "Function", override returns type "Expr | Unknown"
-       Type "Expr | Unknown" is not assignable to type "Function"
+     Return type mismatch: base method returns type "Function", override returns type "Expr | One | Unknown | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number"
+       Type "Expr | One | Unknown | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number" is not assignable to type "Function"
-   .../projects/sympy/sympy/holonomic/holonomic.py:2633:25 - error: Operator "**" not supported for types "Basic" and "Integer | Unknown | NaN | ComplexInfinity | Rational | Zero | Infinity | NegativeInfinity | Float | Number | Expr | Unbound"
+   .../projects/sympy/sympy/holonomic/holonomic.py:2633:25 - error: Operator "**" not supported for types "Basic" and "Integer | Unknown | NaN | ComplexInfinity | Rational | Zero | Infinity | NegativeInfinity | Float | Number | Expr | One | NegativeOne | Unbound"
+   .../projects/sympy/sympy/integrals/integrals.py:1199:29 - error: "One" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1199:29 - error: "NegativeOne" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1199:29 - error: "Zero" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1199:29 - error: "Integer" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1199:29 - error: "NaN" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1199:29 - error: "ComplexInfinity" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1199:29 - error: "Rational" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1311:32 - error: "One" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1311:32 - error: "NegativeOne" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1311:32 - error: "Zero" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1311:32 - error: "Integer" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1311:32 - error: "NaN" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1311:32 - error: "ComplexInfinity" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/integrals.py:1311:32 - error: "Rational" is not iterable
-   .../projects/sympy/sympy/integrals/tests/test_laplace.py:185:12 - error: Operator "-" not supported for types "MatrixBase | tuple[MatrixBase, Unknown | Expr | Max, Boolean] | tuple[Unknown, Unknown, Unknown] | Unknown" and "Expr | Unknown"
+   .../projects/sympy/sympy/integrals/tests/test_laplace.py:185:12 - error: Operator "-" not supported for types "MatrixBase | tuple[MatrixBase, Unknown | Expr | Max, Boolean] | tuple[Unknown, Unknown, Unknown] | Unknown" and "Expr | ComplexInfinity | NaN | Rational | Zero | Infinity | NegativeInfinity | Float | NotImplementedType | Unknown"
+     Operator "-" not supported for types "MatrixBase" and "ComplexInfinity"
+     Operator "-" not supported for types "MatrixBase" and "NaN"
+     Operator "-" not supported for types "MatrixBase" and "Rational"
+     Operator "-" not supported for types "MatrixBase" and "Infinity"
+     Operator "-" not supported for types "MatrixBase" and "NegativeInfinity"
+     Operator "-" not supported for types "MatrixBase" and "Float"
-     Operator "-" not supported for types "tuple[Unknown, Unknown, Unknown]" and "Expr" (reportOperatorIssue)
+     ... (reportOperatorIssue)
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/tests/test_risch.py:799:16 - error: "One" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/tests/test_risch.py:799:16 - error: "NegativeOne" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/tests/test_risch.py:799:16 - error: "Zero" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/tests/test_risch.py:799:16 - error: "Integer" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/tests/test_risch.py:799:16 - error: "NaN" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/tests/test_risch.py:799:16 - error: "ComplexInfinity" is not iterable
+     "__iter__" method not defined (reportGeneralTypeIssues)
+   .../projects/sympy/sympy/integrals/tests/test_risch.py:799:16 - error: "Rational" is not iterable

... (truncated 40 lines) ...

core (https://github.com/home-assistant/core)
-   .../projects/core/homeassistant/components/aprilaire/climate.py:115:16 - error: Type "int" is not assignable to return type "ClimateEntityFeature"
-     "int" is not assignable to "ClimateEntityFeature" (reportReturnType)
-   .../projects/core/homeassistant/components/zwave_js/cover.py:98:41 - error: Cannot assign to attribute "_attr_supported_features" for class "CoverPositionMixin*"
-     Type "CoverEntityFeature | int" is not assignable to type "CoverEntityFeature | None"
-       Type "int" is not assignable to type "CoverEntityFeature | None"
-         "int" is not assignable to "CoverEntityFeature"
-         "int" is not assignable to "None" (reportAttributeAccessIssue)
-   .../projects/core/homeassistant/components/zwave_js/cover.py:111:13 - error: Operator "|=" not supported for types "CoverEntityFeature | None" and "Literal[CoverEntityFeature.STOP]"
-     Operator "|" not supported for types "None" and "Literal[CoverEntityFeature.STOP]" (reportOperatorIssue)
-   .../projects/core/homeassistant/components/zwave_js/cover.py:266:41 - error: Cannot assign to attribute "_attr_supported_features" for class "CoverTiltMixin*"
-     Type "CoverEntityFeature | int" is not assignable to type "CoverEntityFeature | None"
-       Type "int" is not assignable to type "CoverEntityFeature | None"
-         "int" is not assignable to "CoverEntityFeature"
-         "int" is not assignable to "None" (reportAttributeAccessIssue)
-   .../projects/core/homeassistant/components/zwave_js/cover.py:279:13 - error: Operator "|=" not supported for types "CoverEntityFeature | None" and "Literal[CoverEntityFeature.STOP_TILT]"
-     Operator "|" not supported for types "None" and "Literal[CoverEntityFeature.STOP_TILT]" (reportOperatorIssue)
- 43790 errors, 84 warnings, 0 informations
+ 43785 errors, 84 warnings, 0 informations

pandas-stubs (https://github.com/pandas-dev/pandas-stubs)
+   .../projects/pandas-stubs/tests/scalars/test_scalars.py:563:54 - error: Unnecessary "# pyright: ignore" rule: "reportAssertTypeFailure" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/tests/scalars/test_scalars.py:604:54 - error: Unnecessary "# pyright: ignore" rule: "reportAssertTypeFailure" (reportUnnecessaryTypeIgnoreComment)
- 212 errors, 3 warnings, 0 informations
+ 214 errors, 3 warnings, 0 informations

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

mypy_primer analysis

Advisory AI analysis of primer run 42318112960, attempt 1
for commit c23c624754b48eb09239391e33bb61b280419a1d. 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: Reflected-operator priority expands several SymPy arithmetic results into concrete singleton/numeric unions, newly rejecting iteration and .q access while improving two Quaternion returns.

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

Before / baseline evidence: The recorded baseline did not report the per-alternative non-iterability errors at integrals.py:1199 and :1311 or the missing .q errors at utilities/tests/test_wester.py:403. It did report Expr-not-Quaternion return errors at quaternion.py:726 and :1708. Existing failures at numbers.py:1089, holonomic.py:2633, and test_laplace.py:185 already existed; some changed only in union detail/order. No raw evidence shows Any/Unknown erasure or an added assert_type failure.

After / PR evidence: At integrals.py:1199 and :1311, the candidate separately reports One, NegativeOne, Zero, Integer, NaN, ComplexInfinity, and Rational as non-iterable; test_risch.py:799 shows the same mechanism. At test_wester.py:403, ComplexInfinity, NaN, Infinity, NegativeInfinity, and Float are now explicit alternatives lacking .q. add.py:352 also gains an Expr-to-Number assignment error. Conversely, the two Quaternion return errors disappear. Detail-only changes elsewhere mostly reorder or expand existing unions and should not be counted as new locations.

Why this matters: Valid symbolic code can now be rejected when an arithmetic expression is represented as a union containing concrete SymPy numeric singleton classes rather than the prior common Expr abstraction. Users can no longer rely on iteration or Rational-style member access being accepted after those operations. This is increased checking, not precision loss to Any, but it may be a false positive if the reflected return union ignores runtime normalization. Quaternion-producing operators gain useful precision, so the project is mixed.

Causal analysis:

At the exact PR head, shouldPrioritizeReflectedMethod detects a declared strict right subclass with a distinct reflected implementation. validateArithmeticOperation then calls that reflected method before the left forward method and retains its accepted return; explicit NotImplemented declines can be combined with the forward result. SymPy's numeric hierarchy has many strict subclasses and reflected arithmetic methods, so the same operands now flow through subclass return annotations first. That directly explains concrete One/NaN/Float/etc. alternatives appearing where the baseline had Expr/Unknown, and also explains why Quaternion results can become precise enough to remove return errors. The new alternatives trigger iterable and attribute checks rather than suppressing them. Runtime dispatch precedence supports trying the reflected method first, but the raw evidence does not establish that each broad reflected annotation is a realizable result at these call sites; the burst of alternative-specific errors at existing symbolic code is therefore a credible checker regression. Current SymPy source links are contextual only: the exact primer revision was not available, and the source-run logs did not expose the synthetic merge SHA.

Uncertainty / next check: Check one affected expression at integrals.py:1199 with reveals for the left operand, right strict subclass, selected __r*__ overload, and result on both recorded checkouts. Positive control: a right subclass whose reflected method returns a distinct iterable. Negative control: the same hierarchy without a distinct reflected declaration; only the positive case should change.

  • The PR-head predicate prioritizes a distinct reflected implementation on a declared strict right subclass.:
    // cut off the literal union and fall back to the non-literal supertype.
    const maxLiteralMathSubtypeCount = 64;
    function shouldPrioritizeReflectedMethod(
    evaluator: TypeEvaluator,
    leftType: Type,
    rightType: Type,
    methodName: string
    ): boolean {
    if (
    !isClassInstance(leftType) ||
    !isClassInstance(rightType) ||
    // A synthesized narrowing intersection is not evidence of a runtime subclass.
    !rightType.shared.declaration ||
    ClassType.isSameGenericClass(leftType, rightType) ||
    !rightType.shared.mro.some(
    (base) =>
    isInstantiableClass(base) && ClassType.isSameGenericClass(base, ClassType.cloneAsInstantiable(leftType))
    )
    ) {
    return false;
    }
    const rightMember = getClassMemberIterator(rightType, methodName, MemberAccessFlags.SkipInstanceMembers).next()
    .value;
    const leftMember = getClassMemberIterator(leftType, methodName, MemberAccessFlags.SkipInstanceMembers).next().value;
    if (!rightMember || rightMember.symbol === leftMember?.symbol) {
    return false;
    }
    const rightMethod = evaluator.getTypeOfMember(rightMember);
    const leftMethod = leftMember ? evaluator.getTypeOfMember(leftMember) : undefined;
    const rightFunction = isOverloaded(rightMethod) ? OverloadedType.getOverloads(rightMethod)[0] : rightMethod;
    const leftFunction =
    leftMethod && isOverloaded(leftMethod) ? OverloadedType.getOverloads(leftMethod)[0] : leftMethod;
    // Compare unbound declarations, not specialized signatures: aliases and
    // inherited generic methods can have different signatures but the same implementation.
    return (
    !!rightFunction &&
    isFunction(rightFunction) &&
    !!rightFunction.shared.declaration &&
    (!leftFunction ||
    (isFunction(leftFunction) && rightFunction.shared.declaration !== leftFunction.shared.declaration))
    );
    }
    function removeNotImplemented(type: Type): Type {
    return mapSubtypes(type, (subtype) =>
    isClassInstance(subtype) && subtype.shared.fullName === 'types.NotImplementedType' ? undefined : subtype
    );
  • The arithmetic path invokes the reflected method first and can combine an explicit decline with the forward result.:
    }
    }
    const [magicMethodName, altMagicMethodName] = binaryOperatorMap[operator];
    let resultTypeResult: TypeResult | undefined;
    let decliningReflectedResult: TypeResult | undefined;
    let skipReflectedFallback = false;
    // Rich comparisons have different precedence rules. Leave their
    // dispatch, and all ordinary forward-first arithmetic, unchanged.
    if (
    altMagicMethodName.startsWith('__r') &&
    shouldPrioritizeReflectedMethod(
    evaluator,
    leftSubtypeExpanded,
    rightSubtypeExpanded,
    altMagicMethodName
    )
    ) {
    const reflectedResult = evaluator.getTypeOfMagicMethodCall(
    rightSubtypeUnexpanded,
    altMagicMethodName,
    [{ type: leftSubtypeUnexpanded, isIncomplete: leftTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (reflectedResult) {
    const acceptedType = removeNotImplemented(reflectedResult.type);
    if (acceptedType === reflectedResult.type) {
    resultTypeResult = reflectedResult;
    } else if (
    reflectedResult.overloadsUsedForCall?.length &&
    reflectedResult.overloadsUsedForCall.every(
    (overload) => overload.shared.declaredReturnType !== undefined
    )
    ) {
    // Only an explicit return contract establishes a decline;
    // an inherited method's inferred sentinel may be contextual.
    decliningReflectedResult = { ...reflectedResult, type: acceptedType };
    skipReflectedFallback = true;
    }
    }
    }
    resultTypeResult ??= evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, leftSubtypeUnexpanded),
    magicMethodName,
    [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (!resultTypeResult && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
    // Try the expanded left type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, leftSubtypeExpanded),
    magicMethodName,
    [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    }
    if (!resultTypeResult && rightSubtypeUnexpanded !== rightSubtypeExpanded) {
    // Try the expanded left and right type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, leftSubtypeExpanded),
    magicMethodName,
    [{ type: rightSubtypeExpanded, isIncomplete: rightTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    }
    if (skipReflectedFallback && resultTypeResult) {
    const acceptedType = removeNotImplemented(resultTypeResult.type);
    if (
    acceptedType !== resultTypeResult.type &&
    !(
    resultTypeResult.overloadsUsedForCall?.length &&
    resultTypeResult.overloadsUsedForCall.every(
    (overload) => overload.shared.declaredReturnType !== undefined
    )
    )
    ) {
    decliningReflectedResult = undefined;
    } else {
    resultTypeResult =
    acceptedType !== resultTypeResult.type && isNever(acceptedType)
    ? undefined
    : { ...resultTypeResult, type: acceptedType };
    }
    }
    if (!resultTypeResult && !skipReflectedFallback) {
    // Try the alternate form (swapping right and left).
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, rightSubtypeUnexpanded),
    altMagicMethodName,
    [{ type: leftSubtypeUnexpanded, isIncomplete: leftTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (!resultTypeResult && rightSubtypeUnexpanded !== rightSubtypeExpanded) {
    // Try the expanded right type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, rightSubtypeExpanded),
    altMagicMethodName,
    [
    {
    type: leftSubtypeUnexpanded,
    isIncomplete: leftTypeResult.isIncomplete,
    },
    ],
    errorNode,
    inferenceContext
    );
    }
    if (!resultTypeResult && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
    // Try the expanded right and left type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, rightSubtypeExpanded),
    altMagicMethodName,
    [{ type: leftSubtypeExpanded, isIncomplete: leftTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    }
    }
    if (decliningReflectedResult && (resultTypeResult || !isNever(decliningReflectedResult.type))) {
  • Current upstream context for two recorded affected sites; this commit is not proven to be the primer revision.: https://github.com/sympy/sympy/blob/c508f90ea0b0c33169eb11ca2e1705ca2233e996/sympy/integrals/integrals.py#L1199-L1311
Other project assessments

core: Integer-left IntFlag combinations now retain the Home Assistant feature enum, removing false int assignment, return, and |= errors without erasing the enum API.

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

Before / baseline evidence: The recorded baseline treated feature accumulation as int in aprilaire/climate.py:115, rejecting the result against ClimateEntityFeature. In zwave_js/cover.py:98 and :266, assigning a feature expression produced CoverEntityFeature | int against CoverEntityFeature | None; subsequent |= at :111 and :279 also failed because None/int remained in the inferred path. These were observed diagnostics, not assertion expectations.

After / PR evidence: All five diagnostics disappear. The affected pattern starts from an integer zero or combines an integer-valued expression with a ClimateEntityFeature/CoverEntityFeature member. The candidate's reflected-operator path lets the stricter IntFlag subclass determine the result, preserving ClimateEntityFeature or CoverEntityFeature through assignment and later |=. There is no indication that the result became Any or Unknown; the removed errors are consistent with stronger enum precision.

Why this matters: Downstream code can accumulate feature flags from 0, return the declared feature enum, assign it to enum-typed attributes, and continue OR-ing members without casts. It also retains enum members and methods rather than degrading to bare int. The prior diagnostics discouraged a normal IntFlag construction pattern even though Python gives the strict right subclass's reflected implementation priority.

Causal analysis:

At the PR head, shouldPrioritizeReflectedMethod recognizes when the right operand is a declared strict subclass and its reflected method has a different declaration. validateArithmeticOperation then evaluates that reflected method before int.__or__. Home Assistant's feature classes are IntFlag subclasses, so expressions such as 0 | ClimateEntityFeature.TARGET_TEMPERATURE and integer-left CoverEntityFeature combinations follow the enum reflected method and retain the enum type instead of int. PR tests include value | KeepFlag.A yielding KeepFlag and augmented assignments, while preserving int for EJECT cases that can escape the enum. That causal path matches all five removals and preserves, rather than suppresses, useful checking. Confidence is medium because the exact synthetic merge checkout and exact ecosystem revision were not resolved from the available source-run logs; the pinned Home Assistant link is current context, not proof of the recorded revision.

Uncertainty / next check: Confirm the recorded Home Assistant revision's feature enums use standard IntFlag reflected methods and non-EJECT behavior. Minimal controls: reveal_type(0 | Feature.A) should be Feature and permit .name; an EJECT IntFlag with an out-of-mask int should reveal int and reject .name.

  • Exact PR-head logic identifies a strict right subclass with a distinct reflected operator implementation.:
    // cut off the literal union and fall back to the non-literal supertype.
    const maxLiteralMathSubtypeCount = 64;
    function shouldPrioritizeReflectedMethod(
    evaluator: TypeEvaluator,
    leftType: Type,
    rightType: Type,
    methodName: string
    ): boolean {
    if (
    !isClassInstance(leftType) ||
    !isClassInstance(rightType) ||
    // A synthesized narrowing intersection is not evidence of a runtime subclass.
    !rightType.shared.declaration ||
    ClassType.isSameGenericClass(leftType, rightType) ||
    !rightType.shared.mro.some(
    (base) =>
    isInstantiableClass(base) && ClassType.isSameGenericClass(base, ClassType.cloneAsInstantiable(leftType))
    )
    ) {
    return false;
    }
    const rightMember = getClassMemberIterator(rightType, methodName, MemberAccessFlags.SkipInstanceMembers).next()
    .value;
    const leftMember = getClassMemberIterator(leftType, methodName, MemberAccessFlags.SkipInstanceMembers).next().value;
    if (!rightMember || rightMember.symbol === leftMember?.symbol) {
    return false;
    }
    const rightMethod = evaluator.getTypeOfMember(rightMember);
    const leftMethod = leftMember ? evaluator.getTypeOfMember(leftMember) : undefined;
    const rightFunction = isOverloaded(rightMethod) ? OverloadedType.getOverloads(rightMethod)[0] : rightMethod;
    const leftFunction =
    leftMethod && isOverloaded(leftMethod) ? OverloadedType.getOverloads(leftMethod)[0] : leftMethod;
    // Compare unbound declarations, not specialized signatures: aliases and
    // inherited generic methods can have different signatures but the same implementation.
    return (
    !!rightFunction &&
    isFunction(rightFunction) &&
    !!rightFunction.shared.declaration &&
    (!leftFunction ||
    (isFunction(leftFunction) && rightFunction.shared.declaration !== leftFunction.shared.declaration))
    );
    }
    function removeNotImplemented(type: Type): Type {
    return mapSubtypes(type, (subtype) =>
    isClassInstance(subtype) && subtype.shared.fullName === 'types.NotImplementedType' ? undefined : subtype
    );
  • The changed arithmetic branch evaluates the right reflected method before the left forward method.:
    }
    }
    const [magicMethodName, altMagicMethodName] = binaryOperatorMap[operator];
    let resultTypeResult: TypeResult | undefined;
    let decliningReflectedResult: TypeResult | undefined;
    let skipReflectedFallback = false;
    // Rich comparisons have different precedence rules. Leave their
    // dispatch, and all ordinary forward-first arithmetic, unchanged.
    if (
    altMagicMethodName.startsWith('__r') &&
    shouldPrioritizeReflectedMethod(
    evaluator,
    leftSubtypeExpanded,
    rightSubtypeExpanded,
    altMagicMethodName
    )
    ) {
    const reflectedResult = evaluator.getTypeOfMagicMethodCall(
    rightSubtypeUnexpanded,
    altMagicMethodName,
    [{ type: leftSubtypeUnexpanded, isIncomplete: leftTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (reflectedResult) {
    const acceptedType = removeNotImplemented(reflectedResult.type);
    if (acceptedType === reflectedResult.type) {
    resultTypeResult = reflectedResult;
    } else if (
    reflectedResult.overloadsUsedForCall?.length &&
    reflectedResult.overloadsUsedForCall.every(
    (overload) => overload.shared.declaredReturnType !== undefined
    )
    ) {
    // Only an explicit return contract establishes a decline;
    // an inherited method's inferred sentinel may be contextual.
    decliningReflectedResult = { ...reflectedResult, type: acceptedType };
    skipReflectedFallback = true;
    }
    }
    }
    resultTypeResult ??= evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, leftSubtypeUnexpanded),
    magicMethodName,
    [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (!resultTypeResult && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
  • Current upstream context shows feature accumulation from integer zero and a ClimateEntityFeature return; not proven to be the primer revision.: https://github.com/home-assistant/core/blob/f4e3a420d981b8a523fad8614923ffbc18494741/homeassistant/components/aprilaire/climate.py#L99-L115

pandas-stubs: Two Timedelta scalar assertions now match their expected static types, making old reportAssertTypeFailure suppressions obsolete rather than losing checking.

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

Before / baseline evidence: At tests/scalars/test_scalars.py:563 and :604, the baseline did not flag the reportAssertTypeFailure-specific ignores as unnecessary, consistent with those ignores suppressing assertion mismatches. The raw diff does not include the baseline inferred types, so the assertions' expected types must not be presented as observed baseline reveals. No added assertion failure or Any/Unknown erasure is recorded.

After / PR evidence: The candidate emits reportUnnecessaryTypeIgnoreComment at both locations because reportAssertTypeFailure is no longer produced. Thus the same Timedelta-related expressions satisfy the tests' expected static types, while ignore hygiene now asks maintainers to remove stale suppressions. The raw artifact alone does not expose the precise inferred type text, so this conclusion is limited to assertion compatibility rather than claiming an unrecorded reveal.

Why this matters: Consumers gain the narrower operator result expected by these scalar typing tests and no longer need targeted assertion-failure suppressions. Supported operations of that retained scalar type remain checkable; the result did not become bare Any/Unknown. The only migration cost is deleting stale ignores when unnecessary-ignore checking is enabled.

Causal analysis:

The PR changes arithmetic dispatch so a declared strict right subclass with a distinct reflected implementation is evaluated before the left operand's forward method. This is the Python data-model precedence relevant to scalar subclasses and is the same mechanism that changes the recorded Timedelta assertion outcomes. The accepted reflected return is used directly unless an explicit NotImplemented contract requires forward fallback. That can recover the specialized pandas scalar return instead of the less precise left-forward result, causing existing assert_type expectations to pass. The raw diff provides no inferred-type details and the exact pandas-stubs primer revision was unavailable, so the expected type itself is not treated as an observed baseline. Still, two newly stale ignores, no new assertion failures, and no gradual-type signal support an improvement rather than suppressed checking. Current pandas-stubs source is contextual only.

Uncertainty / next check: On the recorded revision, inspect the two expressions, expected assert_type targets, and selected forward/reflected overloads. Controls: a scalar subclass with a distinct __r*__ returning the specialized scalar should satisfy the assertion; aliasing the base reflected implementation should retain the old forward result.

  • Exact PR-head predicate limits reflected priority to declared strict subclasses with a distinct implementation.:
    // cut off the literal union and fall back to the non-literal supertype.
    const maxLiteralMathSubtypeCount = 64;
    function shouldPrioritizeReflectedMethod(
    evaluator: TypeEvaluator,
    leftType: Type,
    rightType: Type,
    methodName: string
    ): boolean {
    if (
    !isClassInstance(leftType) ||
    !isClassInstance(rightType) ||
    // A synthesized narrowing intersection is not evidence of a runtime subclass.
    !rightType.shared.declaration ||
    ClassType.isSameGenericClass(leftType, rightType) ||
    !rightType.shared.mro.some(
    (base) =>
    isInstantiableClass(base) && ClassType.isSameGenericClass(base, ClassType.cloneAsInstantiable(leftType))
    )
    ) {
    return false;
    }
    const rightMember = getClassMemberIterator(rightType, methodName, MemberAccessFlags.SkipInstanceMembers).next()
    .value;
    const leftMember = getClassMemberIterator(leftType, methodName, MemberAccessFlags.SkipInstanceMembers).next().value;
    if (!rightMember || rightMember.symbol === leftMember?.symbol) {
    return false;
    }
    const rightMethod = evaluator.getTypeOfMember(rightMember);
    const leftMethod = leftMember ? evaluator.getTypeOfMember(leftMember) : undefined;
    const rightFunction = isOverloaded(rightMethod) ? OverloadedType.getOverloads(rightMethod)[0] : rightMethod;
    const leftFunction =
    leftMethod && isOverloaded(leftMethod) ? OverloadedType.getOverloads(leftMethod)[0] : leftMethod;
    // Compare unbound declarations, not specialized signatures: aliases and
    // inherited generic methods can have different signatures but the same implementation.
    return (
    !!rightFunction &&
    isFunction(rightFunction) &&
    !!rightFunction.shared.declaration &&
    (!leftFunction ||
    (isFunction(leftFunction) && rightFunction.shared.declaration !== leftFunction.shared.declaration))
    );
    }
    function removeNotImplemented(type: Type): Type {
    return mapSubtypes(type, (subtype) =>
    isClassInstance(subtype) && subtype.shared.fullName === 'types.NotImplementedType' ? undefined : subtype
    );
  • The changed branch uses the reflected return first and handles explicit NotImplemented fallback without global Any widening.:
    }
    }
    const [magicMethodName, altMagicMethodName] = binaryOperatorMap[operator];
    let resultTypeResult: TypeResult | undefined;
    let decliningReflectedResult: TypeResult | undefined;
    let skipReflectedFallback = false;
    // Rich comparisons have different precedence rules. Leave their
    // dispatch, and all ordinary forward-first arithmetic, unchanged.
    if (
    altMagicMethodName.startsWith('__r') &&
    shouldPrioritizeReflectedMethod(
    evaluator,
    leftSubtypeExpanded,
    rightSubtypeExpanded,
    altMagicMethodName
    )
    ) {
    const reflectedResult = evaluator.getTypeOfMagicMethodCall(
    rightSubtypeUnexpanded,
    altMagicMethodName,
    [{ type: leftSubtypeUnexpanded, isIncomplete: leftTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (reflectedResult) {
    const acceptedType = removeNotImplemented(reflectedResult.type);
    if (acceptedType === reflectedResult.type) {
    resultTypeResult = reflectedResult;
    } else if (
    reflectedResult.overloadsUsedForCall?.length &&
    reflectedResult.overloadsUsedForCall.every(
    (overload) => overload.shared.declaredReturnType !== undefined
    )
    ) {
    // Only an explicit return contract establishes a decline;
    // an inherited method's inferred sentinel may be contextual.
    decliningReflectedResult = { ...reflectedResult, type: acceptedType };
    skipReflectedFallback = true;
    }
    }
    }
    resultTypeResult ??= evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, leftSubtypeUnexpanded),
    magicMethodName,
    [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (!resultTypeResult && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
    // Try the expanded left type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, leftSubtypeExpanded),
    magicMethodName,
    [{ type: rightSubtypeUnexpanded, isIncomplete: rightTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    }
    if (!resultTypeResult && rightSubtypeUnexpanded !== rightSubtypeExpanded) {
    // Try the expanded left and right type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, leftSubtypeExpanded),
    magicMethodName,
    [{ type: rightSubtypeExpanded, isIncomplete: rightTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    }
    if (skipReflectedFallback && resultTypeResult) {
    const acceptedType = removeNotImplemented(resultTypeResult.type);
    if (
    acceptedType !== resultTypeResult.type &&
    !(
    resultTypeResult.overloadsUsedForCall?.length &&
    resultTypeResult.overloadsUsedForCall.every(
    (overload) => overload.shared.declaredReturnType !== undefined
    )
    )
    ) {
    decliningReflectedResult = undefined;
    } else {
    resultTypeResult =
    acceptedType !== resultTypeResult.type && isNever(acceptedType)
    ? undefined
    : { ...resultTypeResult, type: acceptedType };
    }
    }
    if (!resultTypeResult && !skipReflectedFallback) {
    // Try the alternate form (swapping right and left).
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, rightSubtypeUnexpanded),
    altMagicMethodName,
    [{ type: leftSubtypeUnexpanded, isIncomplete: leftTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    if (!resultTypeResult && rightSubtypeUnexpanded !== rightSubtypeExpanded) {
    // Try the expanded right type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, rightSubtypeExpanded),
    altMagicMethodName,
    [
    {
    type: leftSubtypeUnexpanded,
    isIncomplete: leftTypeResult.isIncomplete,
    },
    ],
    errorNode,
    inferenceContext
    );
    }
    if (!resultTypeResult && leftSubtypeUnexpanded !== leftSubtypeExpanded) {
    // Try the expanded right and left type.
    resultTypeResult = evaluator.getTypeOfMagicMethodCall(
    convertFunctionToObject(evaluator, rightSubtypeExpanded),
    altMagicMethodName,
    [{ type: leftSubtypeExpanded, isIncomplete: leftTypeResult.isIncomplete }],
    errorNode,
    inferenceContext
    );
    }
    }
    if (decliningReflectedResult && (resultTypeResult || !isNever(decliningReflectedResult.type))) {
  • Current upstream context for the two recorded assertion-ignore locations; this commit is not proven to be the primer revision.: https://github.com/pandas-dev/pandas-stubs/blob/96c49cbe8918f14da9bd7e0dfde6fc7767f72f58/tests/scalars/test_scalars.py#L563-L604

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

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Compared candidate c0127e61d8137cce36e0673278bb342f94516a9e against its first parent 500dd234ac78bb9bf314590591a7c0b2fdf99cef.

View the full release history charts with the base and PR results.

Execution time history

Execution time history

Peak memory history

Peak memory history

Download the chart artifact.

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 15.685s -0.4% 1089.9 MB -0.1% 🟢 Pass
click pyright 17 1.985s +2.1% 358.5 MB +0.4% 🟢 Pass
homeassistant pyright 9850 137.733s -4.2% 6082.5 MB -0.1% 🟢 Pass
numpy pyright 356 28.349s -0.3% 1329.2 MB +5.2% 🟢 Pass
pandas pyright 1459 135.667s -4.0% 3646.4 MB +3.7% 🟢 Pass
pytest pyright 243 9.883s +0.4% 881.7 MB +2.4% 🟢 Pass
requests pyright 19 1.856s -0.7% 342.9 MB +0.5% 🟢 Pass
torch pyright 2400 146.116s -0.2% 5004.3 MB -0.5% 🟢 Pass
transformers pyright 2901 95.345s +2.4% 4958.1 MB -0.8% 🟢 Pass

Pyright stats

Package Parsed/bound Checked Find Read Tokenize Parse Imports Bind Check Cycles
ansible 988 583 0.030s 0.077s 0.297s 0.577s 0.167s 0.767s 13.103s 0.000s
click 111 17 0.000s 0.013s 0.070s 0.137s 0.027s 0.170s 1.367s 0.000s
homeassistant 11150 9850 0.697s 0.707s 2.710s 4.653s 1.897s 6.210s 120.280s 0.000s
numpy 606 356 0.010s 0.047s 0.280s 0.567s 0.183s 0.713s 25.823s 0.000s
pandas 1899 1459 0.070s 0.230s 1.220s 2.443s 0.290s 2.560s 127.837s 0.000s
pytest 545 243 0.010s 0.047s 0.293s 0.437s 0.083s 0.570s 8.070s 0.000s
requests 167 19 0.000s 0.010s 0.093s 0.160s 0.040s 0.203s 1.080s 0.000s
torch 3078 2400 0.187s 0.383s 1.940s 3.607s 0.613s 4.697s 132.387s 0.000s
transformers 3536 2901 0.120s 0.313s 1.677s 2.977s 0.750s 7.047s 81.370s 0.000s

@rchiodo
Rich Chiodo (rchiodo) merged commit bcdd892 into microsoft:main Nov 9, 2026
11 checks passed
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.

Type narrowing not done correctly for bitwise operations with int and instance of subclass of enum.IntFlag

3 participants