Repository navigation
Fix IntFlag bitwise narrowing with localized reflected-operator priority - #11977
Rich Chiodo (rchiodo) merged 4 commits into
Conversation
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>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
🔴 Pyright CLI QA —
|
This comment has been minimized.
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>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
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:
That accounts for +1 +21 +5 -2 = +25. There are 20 rewritten existing diagnostic groups overall. In particular, the advisory's unpacking and The new dictionary diagnostic was checked at the exact caller. With actual SymPy imports, I executed 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 |
|
The new flag mask proof can hide a real Custom
|
| 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 | 1The 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>
|
Heejae Chang (@heejaechang) Fixed both in 6889680. The storage guard now checks for custom 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: 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 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>
|
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
|
mypy_primer analysisAdvisory AI analysis of primer run 42318112960, attempt 1 Regression review required. Potential regressions or recorded warning signals are listed first; causation must be established separately. Potential regressionssympy: 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.
Other project assessmentscore: 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.
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.
Full evidence and limitations: download |
|
Compared candidate View the full release history charts with the base and PR results. Execution time historyPeak memory historyType checker benchmark🟢 No performance regressions detected. Regression threshold:
Pyright stats
|
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, andint() ^ Flags.Arevealingintinstead ofFlags.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
NotImplementedfrom 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
git diff --checkpassed.The SymPy widening follows reflected dispatch. A runtime probe at the exact
Add.flattenassignment confirms Number operands can store a non-NumberAddcoefficient with evaluation disabled, including throughAdd(..., evaluate=True). Keeping an unconditionalNumberresult 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
NotImplementedprecision issues are not addressed. No clean performance comparison has been performed.Validated base:
b57fefae2650597bd1a0f7fb3ce821015c25d317, including the receiver-binding fix in #11953.