Repository navigation
Narrow bare Final for reachability, give static conditions literal types - #12057
crypt0lith wants to merge 7 commits into
Conversation
Reachability narrows a condition's reference only when its symbol has typed declarations, which excludes a bare Final, and never for a module member access. Accept a Final assigned a value in its declaration, imported or as 'module.NAME', and classify a branch pruned by a Final with a literal type as a static condition. Fixes microsoft#11980
A statically evaluated condition received a literal type only as the right side of an assignment, so 'sys.platform == "win32"' was bool as an argument or an operand. Assign the literal type wherever a bool-typed name, member access, unary or binary operation evaluates statically, and remove the assignment special case.
🔴 Pyright CLI QA —
|
|
The first finding in #12057 (comment) (run: e7312d1) isn't new behavior -- it is in fact one of the oldest. def check(TYPE_CHECKING: bool) -> None:
x = TYPE_CHECKING
reveal_type(x)This PR applies that conversion to every expression, not only the right side of an assignment, so the argument case now shows it too. |
|
The tuple-subclass findings in #12057 (comment) (run: 6843464) aren't new behavior. The base's The class Base:
pass
def f(x: Base):
reveal_type(x or "x")
>>> bool(object())
TrueThe comment on that check already calls out the gap ( |
|
Diff from mypy_primer, showing the effect of this PR on open source code: sympy (https://github.com/sympy/sympy)
- .../projects/sympy/sympy/concrete/summations.py:1389:12 - error: Operator "*" not supported for types "Expr | Basic | Any | Unknown" and "Basic"
+ .../projects/sympy/sympy/concrete/summations.py:1389:12 - error: Operator "*" not supported for types "Expr | Unknown" and "Basic"
- Operator "*" not supported for types "Expr" and "Basic"
- Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:468:32 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:469:28 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:473:23 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:474:24 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:478:25 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:480:40 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:481:54 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:484:54 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:485:40 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:487:55 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:488:41 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:489:41 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:490:55 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:493:20 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:494:35 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:496:21 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:499:19 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:500:25 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:502:25 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:504:20 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:506:26 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:510:22 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:513:29 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:514:30 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:519:14 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:520:14 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:523:14 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:524:14 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:535:14 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:538:14 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:543:14 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:544:14 - error: "is_negative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:547:14 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:548:14 - error: "is_positive" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:587:27 - error: "is_nonnegative" is not a known attribute of "None" (reportOptionalMemberAccess)
+ .../projects/sympy/sympy/core/tests/test_exprtools.py:588:28 - error: "is_nonpositive" is not a known attribute of "None" (reportOptionalMemberAccess)
- .../projects/sympy/sympy/integrals/meijerint.py:1491:13 - error: Index 0 is out of range for type tuple[()] (reportGeneralTypeIssues)
- .../projects/sympy/sympy/integrals/meijerint.py:1493:18 - error: Cannot access attribute "base" for class "Expr"
- Attribute "base" is unknown (reportAttributeAccessIssue)
- .../projects/sympy/sympy/integrals/meijerint.py:1493:37 - error: Cannot access attribute "exp" for class "Expr"
- Attribute "exp" is unknown (reportAttributeAccessIssue)
- .../projects/sympy/sympy/integrals/tests/test_meijerint.py:496:23 - error: Argument of type "Unknown | Basic" cannot be assigned to parameter "expr" of type "Expr" in function "expand_mul"
- Type "Unknown | Basic" is not assignable to type "Expr"
- "Basic" is not assignable to "Expr" (reportArgumentType)
- .../projects/sympy/sympy/polys/rootoftools.py:1197:26 - error: Operator "*" not supported for types "int" and "Basic | Unknown | Self@RootSum | Expr"
- Operator "*" not supported for types "int" and "Basic" (reportOperatorIssue)
- .../projects/sympy/sympy/series/limitseq.py
- .../projects/sympy/sympy/series/limitseq.py:134:25 - error: Cannot access attribute "as_numer_denom" for class "Basic"
- Attribute "as_numer_denom" is unknown (reportAttributeAccessIssue)
- .../projects/sympy/sympy/series/limitseq.py:149:25 - error: Cannot access attribute "as_numer_denom" for class "Basic"
- Attribute "as_numer_denom" is unknown (reportAttributeAccessIssue)
- .../projects/sympy/sympy/simplify/fu.py:994:35 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
- Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
- "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
- Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
- "Basic" is not assignable to "Expr" (reportArgumentType)
- .../projects/sympy/sympy/simplify/fu.py:1006:39 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
- Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
- "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
- Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
- "Basic" is not assignable to "Expr" (reportArgumentType)
- .../projects/sympy/sympy/simplify/fu.py:1028:43 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
- Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
- "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
- Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
- "Basic" is not assignable to "Expr" (reportArgumentType)
- .../projects/sympy/sympy/simplify/fu.py:1039:47 - error: Argument of type "Unknown | tuple[Basic, ...]" cannot be assigned to parameter "iterable" of type "Iterable[Expr]" in function "extend"
- Type "Unknown | tuple[Basic, ...]" is not assignable to type "Iterable[Expr]"
- "tuple[Basic, ...]" is not assignable to "Iterable[Expr]"
- Type parameter "_T_co@Iterable" is covariant, but "Basic" is not a subtype of "Expr"
- "Basic" is not assignable to "Expr" (reportArgumentType)
- .../projects/sympy/sympy/simplify/simplify.py:166:20 - error: Argument of type "dict[str, Unknown] | dict[Unknown, list[Unknown]] | Expr | Abs | Unknown | Basic | None" cannot be assigned to parameter "b" of type "Expr | complex" in function "__new__"
... (truncated 193 lines) ...
scikit-learn (https://github.com/scikit-learn/scikit-learn)
- .../projects/scikit-learn/sklearn/linear_model/_least_angle.py:803:34 - error: Argument of type "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" cannot be assigned to parameter "key" of type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" in function "__getitem__"
+ .../projects/scikit-learn/sklearn/linear_model/_least_angle.py:803:34 - error: Argument of type "tuple[slice[None, int, None], slice[int, None, None]]" cannot be assigned to parameter "key" of type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" in function "__getitem__"
- Type "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" is not assignable to type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]"
+ Type "tuple[slice[None, int, None], slice[int, None, None]]" is not assignable to type "SupportsIndex | slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]"
- "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" is incompatible with protocol "SupportsIndex"
+ "tuple[slice[None, int, None], slice[int, None, None]]" is incompatible with protocol "SupportsIndex"
- "tuple[slice[None, int | Unknown, None], slice[int | Unknown, None, None]]" is not assignable to "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" (reportArgumentType)
+ "tuple[slice[None, int, None], slice[int, None, None]]" is not assignable to "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" (reportArgumentType)
pandera (https://github.com/pandera-dev/pandera)
- .../projects/pandera/pandera/api/pandas/model.py:290:68 - error: Argument of type "dict[str, Any | str | None]" cannot be assigned to parameter "dtype" of type "AstypeArg | Mapping[Any, Dtype] | Series[Any]" in function "astype"
- Type "dict[str, Any | str | None]" is not assignable to type "AstypeArg | Mapping[Any, Dtype] | Series[Any]"
- Type "dict[str, Any | str | None]" is not assignable to type "type[bool]"
- "dict[str, Any | str | None]" is not assignable to "BooleanDtype"
- Type "dict[str, Any | str | None]" is not assignable to type "type[numpy.bool[builtins.bool]]"
- Type "dict[str, Any | str | None]" is not assignable to type "type[int]"
- "dict[str, Any | str | None]" is not assignable to "Int8Dtype"
- "dict[str, Any | str | None]" is not assignable to "Int16Dtype"
- "dict[str, Any | str | None]" is not assignable to "Int32Dtype"
- ... (reportArgumentType)
- 3858 errors, 201 warnings, 0 informations
+ 3857 errors, 201 warnings, 0 informations
apprise (https://github.com/caronc/apprise)
- Return type mismatch: base method returns type "Literal[1]", override returns type "int"
+ Return type mismatch: base method returns type "Literal[1]", override returns type "Literal[0]"
- "int" is not assignable to type "Literal[1]" (reportIncompatibleMethodOverride)
+ "Literal[0]" is not assignable to type "Literal[1]" (reportIncompatibleMethodOverride)
+ .../projects/apprise/apprise/attachment/memory.py:213:9 - error: Method "__len__" overrides class "AttachBase" in an incompatible manner
+ Return type mismatch: base method returns type "Literal[0]", override returns type "int"
+ "int" is not assignable to type "Literal[0]" (reportIncompatibleMethodOverride)
- 7486 errors, 18 warnings, 0 informations
+ 7487 errors, 18 warnings, 0 informations
dd-trace-py (https://github.com/DataDog/dd-trace-py)
- .../projects/dd-trace-py/tests/debugging/exploration/_profiler.py:58:39 - error: Cannot access attribute "__code__" for class "FullyNamedFunction"
- Attribute "__code__" is unknown (reportAttributeAccessIssue)
- Attribute "_encoders" is unknown (reportAttributeAccessIssue)
- .../projects/dd-trace-py/tests/debugging/exploration/debugger.py:144:23 - error: Cannot assign to attribute "_encoders" for class "NoopSnapshotJsonEncoder"
- 13573 errors, 765 warnings, 0 informations
+ 13571 errors, 765 warnings, 0 informations
spack (https://github.com/spack/spack)
- .../projects/spack/lib/spack/spack/test/traverse.py:497:23 - error: Cannot access attribute "parent" for class "tuple[int, DependencySpec]"
- Attribute "parent" is unknown (reportAttributeAccessIssue)
- .../projects/spack/lib/spack/spack/test/traverse.py:497:48 - error: Cannot access attribute "parent" for class "tuple[int, DependencySpec]"
- Attribute "parent" is unknown (reportAttributeAccessIssue)
- Attribute "spec" is unknown (reportAttributeAccessIssue)
- .../projects/spack/lib/spack/spack/test/traverse.py:497:66 - error: Cannot access attribute "spec" for class "tuple[int, DependencySpec]"
- 1891 errors, 20 warnings, 0 informations
+ 1888 errors, 20 warnings, 0 informations
jax (https://github.com/google/jax)
- .../projects/jax/jax/experimental/sparse/bcoo.py:418:25 - error: "int" is not iterable
+ .../projects/jax/jax/experimental/sparse/bcoo.py:418:25 - error: "Literal[1]" is not iterable
- .../projects/jax/jax/experimental/sparse/bcoo.py:1418:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | int" cannot be assigned to target tuple
+ .../projects/jax/jax/experimental/sparse/bcoo.py:1418:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | Literal[1]" cannot be assigned to target tuple
- .../projects/jax/jax/experimental/sparse/bcoo.py:1418:39 - error: "int" is not iterable
+ .../projects/jax/jax/experimental/sparse/bcoo.py:1418:39 - error: "Literal[1]" is not iterable
- .../projects/jax/jax/experimental/sparse/bcoo.py:1534:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | int" cannot be assigned to target tuple
+ .../projects/jax/jax/experimental/sparse/bcoo.py:1534:3 - error: Expression with type "Array | tuple[Array, *tuple[Array, ...], Literal[1]] | tuple[Array, *tuple[Array, ...], Array] | tuple[Array, Array] | tuple[*tuple[Array, ...], Array] | tuple[Array, ...] | Literal[1]" cannot be assigned to target tuple
- .../projects/jax/jax/experimental/sparse/bcoo.py:1534:39 - error: "int" is not iterable
+ .../projects/jax/jax/experimental/sparse/bcoo.py:1534:39 - error: "Literal[1]" is not iterable
alerta (https://github.com/alerta/alerta)
- .../projects/alerta/alerta/database/backends/postgres/base.py:349:105 - error: "attributes" is not a known attribute of "None" (reportOptionalMemberAccess)
- .../projects/alerta/alerta/database/backends/postgres/base.py:369:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
- .../projects/alerta/alerta/database/backends/postgres/base.py:379:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
- .../projects/alerta/alerta/database/backends/postgres/base.py:388:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
- .../projects/alerta/alerta/database/backends/postgres/base.py:397:35 - error: Object of type "None" cannot be used as iterable value (reportOptionalIterable)
- 521 errors, 15 warnings, 0 informations
+ 516 errors, 15 warnings, 0 informations
|
mypy_primer analysisAdvisory AI analysis of primer run 46478689026, attempt 1 Regression review required. Potential regressions or recorded warning signals are listed first; causation must be established separately. Potential regressionssympy: Truthiness-driven branch pruning reshapes many unions and removes several independent attribute, optional, and operator checks; the mixed gains do not establish that the lost checks were unreachable.Regression warning signals require review, regardless of the AI assessment:
AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: The recorded baseline checked both sides of affected flows: e.g. meijerint.py:1491 rejected indexing tuple[()], sqrtdenest.py:303 rejected multiplication by None, single.py:2757 rejected subscripting None, and several Basic-vs-Expr/member errors were reported. These are observed diagnostics, not inferred runtime failures. After / PR evidence: The three highlighted checks disappear. Elsewhere the same run gains None-member checks in test_exprtools.py:468-588 and much wider operator/member diagnostics around sqrtdenest.py:340-635; at sqrtdenest.py:309 a new Expr + (... | None) error partly replaces the old line-303 optional-operand error. This is redistribution of checked paths, not a simple cleanup. Why this matters: Users can no longer rely on Pyright to flag the tuple index, optional subscript, and some Basic member/argument operations on these paths. Conversely, newly reachable paths now expose many optional/member/operator errors. If a condition is not actually invariant, suppressing one branch can hide real static errors without any runtime regression being required. Causal analysis: The PR changes ternary evaluation to call canBeFalsy/canBeTruthy and omit an arm when a condition's type is one-sided, changes truthiness to honor __bool__ before tuple length/__len__, and gives statically evaluated boolean expressions literal types. Those choices feed later flow and expression inference, explaining both narrower unions (Basic disappears at simplify.py:166 and Unknown disappears from summations.py:1389) and newly/previously analyzed branches. The removed checks are credible regressions because no inspected evidence proves their guards constant; the simultaneous new checks are counterevidence to a blanket regression classification but do not restore the lost operations. No type-erasure or assertion-failure signal was recorded; the gradual-detail signal instead shows union-member replacement. The exact ecosystem revision and synthetic merge SHA were unavailable, so current SymPy source was not treated as historical proof. Uncertainty / next check: At each removed site, test the recorded source with a condition type whose __bool__ returns plain bool versus Literal[True]/Literal[False]. A negative control should keep both arms and retain the None/tuple/member error; a positive control with a literal truth value should prune only the impossible arm.
pandera: An astype mapping error disappears after a conditional dtype value loses its None alternative; without the recorded checkout, it is unclear whether that branch is truly impossible.AI assessment: Possible regression (low confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: At model.py:290:68, the baseline rejected dict[str, Any | str | None] as pandas astype's dtype argument and gave detailed incompatibilities with AstypeArg/Mapping[Any, Dtype]/Series[Any]. This was an observed argument check. After / PR evidence: The entire argument diagnostic and its detail disappear. Current upstream has a dtypes comprehension with a conditional value followed by DataFrame(...).astype(dtypes), consistent with a ternary precision change, but current source is not proof of the recorded revision. Why this matters: A caller can no longer rely on Pyright to reject a dtype mapping whose values may include None at this site. If None is genuinely excluded by the condition, this is a useful false-positive removal; if not, the PR has suppressed validation of an invalid mapping. Causal analysis: The PR's ternary path now uses canBeFalsy/canBeTruthy and skips an arm when the condition type is considered one-sided. That can remove the else-None member from a comprehension value, after which Any in the remaining value union can make astype's overload acceptable. This is not evidence of type erasure of the outer dict, but it can still weaken argument checking. Current Pandera source shows the same structural pattern, yet the exact ecosystem commit and synthetic Pyright merge were unavailable. Because no declaration proving the condition always truthy was inspected at the recorded revision, blaming pandas stubs or calling the removal expected would be premature. Uncertainty / next check: Resolve the recorded Pandera commit and inspect the type and truth methods of the comprehension condition. Control with T | None must retain None and the astype error; a non-optional, provably truthy T should select only the dtype arm.
apprise: Literal return inference for inherited __len__ methods becomes subclass-dependent, producing a new override error and changing the old mismatch from int to Literal[0].AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: One override mismatch said a base __len__ returned Literal[1] while the override returned int. This is observed diagnostic detail, not an assertion expectation. After / PR evidence: That mismatch now says the override returns Literal[0], and memory.py:213:9 gains a second error because AttachMemory.__len__ returns int while its base is inferred as Literal[0]. Current AttachMemory explicitly returns its buffer size, an arbitrary nonnegative int. Why this matters: Valid subclasses whose lengths vary can be rejected as incompatible because a base implementation's ternary result is specialized to one literal under the subclass's truthiness. Users can no longer rely on ordinary int-returning __len__ overrides being compared against the base's unspecialized int contract. Causal analysis: The PR makes ternaries one-armed when canBeFalsy/canBeTruthy says their condition is constant and changes __bool__/__len__ precedence. A base __len__ implemented as `1 if self else 0` can therefore infer Literal[1] or Literal[0] rather than int, and inherited analysis appears to vary with subclass truthiness; the changed and additional override diagnostics are the direct symptom. The PR's own tuple-literal test expects this kind of literal narrowing, but applying it to an overridable method contract is counterevidence to treating the ecosystem errors as an unqualified improvement. Current source confirms AttachMemory's varying int length, though the exact analyzed Apprise commit is unavailable. Uncertainty / next check: Minimal control: base `def __len__(self): return 1 if self else 0`, subclass `__bool__ -> Literal[False]`, and subclass `__len__ -> int`. Compare method's declared/inferred contract with call-site specialization; only the call result, not override compatibility, should specialize.
dd-trace-py: Two attribute checks disappear on live exploration-code paths, consistent with truthiness-based branch elimination rather than corrected member types.AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: The baseline rejected `f.__code__` at _profiler.py:58:39 because f could be FullyNamedFunction, and rejected assignment to `_encoders` at debugger.py:144:23 for NoopSnapshotJsonEncoder. Both were concrete attribute-access checks. After / PR evidence: Both diagnostics vanish with no replacement detail and no evidence that the relevant class declarations acquired those members. Current upstream retains analogous accesses, but its revision is not the recorded primer checkout. Why this matters: Users can no longer rely on Pyright to flag an unsupported function-code attribute or private encoder assignment along these paths. If the condition selecting these paths is not statically fixed, real member mistakes are hidden even though runtime may still happen to work dynamically. Causal analysis: The PR converts static boolean expressions to Literal booleans and lets ternary/control-flow reachability consume declared or Final conditions, while truthiness analysis now gives __bool__ precedence. Any configuration or version guard around these exploration paths can therefore become statically one-sided, preventing the member operation from being evaluated. The removed diagnostics are not explained by a stub correction in the PR. However, the raw diff omits unchanged context and the exact dd-trace revision was unavailable, so the precise guarding expression could not be established. That uncertainty prevents a high-confidence causal claim but leaves a credible checker regression. Uncertainty / next check: Resolve the recorded commit and inspect guards around both statements. Negative control with an unconstrained bool must preserve each attribute error; positive control with a valid Final/static platform condition may suppress only the unreachable branch.
spack: All member errors on a tuple-or-edge value disappear together, suggesting one union arm or branch was pruned without evidence that tuple values are impossible.AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: At traverse.py:497, the baseline reported two `.parent` accesses and one `.spec` access on tuple[int, DependencySpec]. The tuple outer type was preserved, so these checks caught a concrete API mismatch rather than element imprecision. After / PR evidence: All three attribute diagnostics disappear and no replacement is recorded. The evidence does not show that the value was retyped to an edge object or that the tuple alternative became unreachable. Why this matters: Downstream code can no longer rely on Pyright to reject edge-style member access when the value may still be a `(depth, edge)` tuple. This loses checks for the tuple's outer API, not merely a generic argument. Causal analysis: The PR's reachability and ternary changes can discard one alternative when a condition is inferred always truthy/falsy, and its truthiness engine specially handles tuple subclasses and __bool__. If line 497 selects between a depth tuple and an edge object, pruning the tuple-producing path removes exactly these three member diagnostics. There is no type-erasure signal, but disappearance of all outer-API checks is independently significant. Current Spack source was inspected only as a nonhistorical reference; the exact primer revision and call-site guard were not resolved, so the causal expression remains uncertain and this cannot be called a proven defect. Uncertainty / next check: Inspect the recorded traversal return annotation and line-497 guard. Control `tuple[int, Edge] | Edge` with plain bool must retain member errors; only a Literal guard that proves the tuple arm impossible should remove them.
alerta: Five None-safety checks disappear from one query-building region, consistent with a nullable branch being declared unreachable rather than the values being narrowed safely.Regression warning signals require review, regardless of the AI assessment:
AI assessment: Possible regression (high confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: At postgres/base.py:349 the baseline rejected `.attributes` on None; at lines 369, 379, 388, and 397 it rejected iterating None. These are distinct observed optional checks in a concentrated control-flow region. After / PR evidence: All five diagnostics vanish with no replacement narrowing detail. The raw evidence does not show assignments or guards that exclude None, and no Alerta declaration change is part of this Pyright PR. Why this matters: Downstream users can no longer rely on Pyright to catch member access or iteration when these database values are absent. This is a loss of None-safety checking even if tests happen not to exercise the runtime path. Causal analysis: The PR broadens static-condition handling: boolean expressions gain literal types, declared/Final references can mark branches unreachable, member-access conditions participate, and ternaries omit arms based on canBeFalsy/canBeTruthy. A condition surrounding this repeated postgres block can therefore eliminate the None-bearing path, removing exactly the optional-member/iterable errors. The clustered loss and explicit removed-check signal make a regression credible. Counterevidence is that the condition could be genuinely static in the configured environment, but the exact Alerta revision and guard were unavailable, so this was not proven. No type erasure was observed; the issue is suppressed analysis of an alternative. Uncertainty / next check: Resolve the recorded file and inspect the shared guard/assignment before lines 349-397. With a plain bool or Optional value, all five checks should remain; with an imported Final Literal condition, only the demonstrably unreachable side should be skipped.
Other project assessmentsscikit-learn: The failing index operation remains checked, while Unknown is removed from both slice endpoints; this is a diagnostic-detail precision gain rather than lost validation.AI assessment: Expected improvement (medium confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: At _least_angle.py:803:34 the baseline rejected the tuple-of-slices key, displaying endpoints as int | Unknown. The key itself was still known as a tuple and the __getitem__ argument error was present. After / PR evidence: The same location and incompatibility remain, but both endpoints are int. No header is truly gained or lost here: the apparent replacement is a message rewrite at one operation with more precise inferred endpoint types. Why this matters: Downstream users retain the invalid-key diagnostic and gain usable int endpoint information. They can rely less on Unknown masking subsequent integer operations; no supported outer API or check disappears in the recorded evidence. Causal analysis: The PR makes statically evaluable boolean expressions literal and uses canBeFalsy/canBeTruthy to select ternary arms. A slice bound produced conditionally can therefore retain only the int arm instead of int | Unknown. This matches the observed endpoint-only refinement while preserving the tuple-key mismatch. The exact scikit-learn checkout was not resolved, so the causal expression at line 803 was not pinned; attribution is nevertheless likely because the only change is precisely the type precision controlled by the PR's ternary path. There is no type-erasure, removed-check, or assertion signal for this project. Uncertainty / next check: Confirm the recorded line's bounds arise from a ternary/static condition. Positive control: a Literal[True] condition yields int endpoints; negative control: plain bool preserves both arms. The invalid tuple key should be diagnosed in both cases.
jax: Five diagnostics are message rewrites: an int alternative is refined to Literal[1], while every iterable/tuple-assignment failure remains at the same location.AI assessment: Expected improvement (high confidence). PR attribution: Likely caused by the PR. Before / baseline evidence: At bcoo.py:418, 1418, and 1534, the baseline diagnosed non-iterable `int` and tuple-target unions ending in `int`. These were observed diagnostics; no outer Array or tuple API was erased. After / PR evidence: The same five locations and errors remain, but each affected `int` is now `Literal[1]`. The union's Array and tuple alternatives are unchanged, so this is added value precision rather than a new or removed check. Why this matters: Users retain all invalid-iteration and tuple-unpacking checks and gain the exact sentinel value responsible. Supported operations are not lost: Literal[1] supports the same int operations while enabling stronger narrowing. Causal analysis: The PR assigns literal types to statically evaluated boolean expressions and changes truthiness-aware ternary inference. A sentinel expression that previously widened to int now remains Literal[1], which propagates into BCOO's shape/result unions. The diagnostic continuity is an important control: unlike projects with vanished headers, Pyright still rejects every invalid iterable/tuple target. The exact JAX revision was unavailable, but the identical locations and otherwise identical unions establish that this is a detail-only precision change, and the PR's literal-preservation tests directly support the attribution. Uncertainty / next check: Confirm the source expression producing 1 at the recorded JAX commit. Positive control should reveal Literal[1] while retaining a non-iterable error; a dynamically computed int should remain int. No assertion-failure or type-erasure signal needs follow-up here.
Full evidence and limitations: download |
|
Compared candidate Release history charts were not rendered for this run. See the workflow run for details. Type checker benchmark🟢 No performance regressions detected. Regression threshold:
Pyright stats
|
|
AFAICT, none of the possible regressions in #12057 (comment) are new behavior. 🤖 AI-assisted findingsalerta and spack are call-site return type inference. alerta's dd-trace-py, pandera and sympy's In apprise, The rest of sympy depends on the order its files are checked in. Checking |
Mangesh Raut (mangeshraut712)
left a comment
There was a problem hiding this comment.
Verified on the PR head: the Final-reachability work from #12002/#12016 carries over, the new getBoolArgValue enables @dataclass(frozen=FINAL), and the focused suites pass. One behavior change worth an explicit decision — module constants without Final now also control frozen=/kw_only=.
✅ Suites
typeEvaluator1/4/8 -t 'Dataclass|StaticExpression|Final|Reachability' → 45 passed on the PR head.
✅ Imported-Final reachability — carries over from #12016
Re-ran the import-shape probe (direct / as-renamed / comparison / repeated import) against this PR: all four prune correctly, main prunes none. The resolveAliasDeclaration(decl, resolveLocalNames=true) path at codeFlowEngine.ts:1418 is doing the work. The three must-still-analyze controls (DYNAMIC, ANNOTATED, PLAIN) hold as in #12016.
✅ The new capability — type-based frozen=/kw_only=
getBoolArgValue replaces the old AST-only evaluateStaticBoolExpression for dataclass bool args. It evaluates the argument's type and uses canBeFalsy/canBeTruthy:
| Declaration | @dataclass(frozen=…) then obj.x = 2 |
main |
PR |
|---|---|---|---|
FREEZE: Final = True (imported) |
A |
accepted | error ✓ |
DYN: bool = True (unknown) |
D |
accepted | accepted ✓ (correctly falls back) |
NOT_FINAL = True (plain module constant) |
C |
accepted | error |
The first two are exactly right. The fallback for a non-literal bool is sound: both canBeFalsy and canBeTruthy return true → undefined → default behaviour.
⚠️ Behavior change to confirm: implicit-Final module constants now count
Row 3 is the one to make a deliberate call on. NOT_FINAL = True has no Final, but Pyright already types it as Literal[True] on main (confirmed with reveal_type) — module-level constants are implicitly Final. So once the check is type-based, @dataclass(frozen=NOT_FINAL) freezes, where on main only a literal True did.
This is consistent with how Pyright already treats such constants everywhere else, and I'd argue it's an improvement (a CONFIG_FROZEN = True in a config module is a common pattern). But it is a user-visible change beyond the description's framing ("narrow bare Final"), and it will surface as new reportAttributeAccessIssue errors on code that previously type-checked. Two suggestions:
- Mention it in the PR description and the changelog entry explicitly, so it's not discovered as a surprise.
- Decide whether
getBoolArgValueshould requireFinal(or an explicitly-literal type) rather than accepting anybool-typed expression whose truthiness is decidable. RequiringLiteral[True]/Literal[False]and a Final/constant declaration would keep the implicit-Final behaviour opt-in by annotation. Either is defensible — it just needs to be chosen.
📝 Minor
The refactor in dataClasses.ts (7 inline evaluateStaticBoolExpression calls → getBoolArgValue) drops the nodeInfo parameter from several functions, which is a nice simplification. The removed evaluateStaticBoolExpression import is no longer referenced — confirmed clean.
canBeFalsy decides a tuple subclass from its tuple length without looking up __bool__ or __len__, so a non-empty subclass whose __bool__ or __len__ can return a falsy value is treated as always truthy. Use the tuple length only when the class has no __bool__ and its __len__ is tuple's, and look up both methods on the class only, as Python does. Fixes microsoft#12074
7a48423 to
62d3f3a
Compare
|
The 62d3f3a removes the The synthesized The |
Summary
Fixes #11980
Fixes #12074
Supersedes #12002, #12016, #12040
Pyright handles static conditions inconsistently depending on the context.
Final[...]. A bareFinaldeclaration is skipped, even though the assigned value's inferred type isLiteral[False]/Literal[True]. DeclaredFinal[...]static conditions are also skipped during reachability checks when the name is imported.boolinstead ofLiteral[False]/Literal[True].bool-typed parameters of special constructs (namedtuple'srename, dataclass anddataclass_transform), as well as for ternary tests.__bool__returnsLiteral[False].__bool__returnsLiteral[False]or its__len__isn't tuple's. Code afterx or yon such an instance is unreachable.ty 0.0.107 and pyright 1.1.414,
--pythonplatform LinuxHow ty handles some of these cases:
reachability.rs:2028-2034types/infer/builder.rs:9211-9226renameby truthiness of its type:types/infer/builder/named_tuple.rs:420-422Root cause
Finalhas none:Finalis a qualifier, so its type is inferred from the assigned value. An imported name has none either, since its declaration is the import, andmodule.NAMEisn't a name. When the check does find the branch unreachable, aFinalwith a literal type is reported byreportUnreachable, unlike the inline static condition.bool.evaluateStaticBoolExpressionreads any name spelledTYPE_CHECKINGasTrue, whatever it refers to.rename, the dataclass anddataclass_transformparameters and the ternary test are evaluated withevaluateStaticBoolExpression, which only reads syntax. An argument of typeLiteral[True]orLiteral[False]is ignored by namedtuple and dataclass,dataclass_transformreports it as not statically evaluated, and the ternary evaluates to both branches.__bool__or__len__.canBeFalsydecides a tuple subclass from its tuple length before looking up__bool__or__len__.Fix
Final, an imported name and a module member access (module.NAME), as for a local name with a declared type. When aFinalwith a literal type makes a branch unreachable, treat the branch like one under an inline static condition, whichreportUnreachabledoesn't report.bool. Replaces the assignment-only conversion. A name spelledTYPE_CHECKINGcounts only when it refers to typing'sTYPE_CHECKINGor to a variable assignedFalse, as in ty.renamewhen it's always truthy, the dataclass parameters when it's a constantbool, and the ternary's branch when the test is constant. TypedDicttotalandclosedstay syntactic, since the spec allows only literalTrueorFalsethere.renameneeds to be considered, not whether it's abool, since an argument of another type is already reported by argument checking.and/orand the ternary.__bool__and its__len__is tuple's. Look up__bool__and__len__on the class without instance attributes, as Python does.__len__that pyright synthesizes for namedtuple classes, which use tuple's at runtime.Test
Cases added to
staticExpression4.pyfunc1Finalplatform check, branch prunedfunc2Finalplatform check, branch prunedfunc3notof an importedFinalplatform check, branch prunedfunc4Finalplatform check imported withas, branch prunedfunc5Final[Literal[False]], branch prunedfunc6module.NAMEFinalplatform check, branch prunedfunc7Finalwhose value isn't static, branch reachablefunc8Final, branch reachablefunc9Finalclass attribute read through an instance, branch reachablefunc10Anyparameter named like the module, branch reachablefunc11isinstanceon aFinalwith a non-literal type, branch reachablefunc12module.NAMEread before the module name is rebound, branch prunedfunc13module.NAMEread after the module name is rebound to an instance, branch reachableCases added to
staticExpression5.pyfunc1os.name,TYPE_CHECKINGandnotchecks are literalfunc2orwith a true static condition isLiteral[True]func3func4Literal[True]func5boolparameter namedTYPE_CHECKINGstaysbool, also undernotfunc6TYPE_CHECKING = FalseisLiteral[True]Cases added to
ternary1.pyfunc1func2func3booltest, both branches' typesfunc4__bool__returnsLiteral[False], false branch's typefunc5func6__bool__and__len__, true branch's typefunc7__bool__returnsLiteral[True]and that defines__len__, true branch's typeCases added to
namedTuple9.pyNT6renamefrom aFinaltrue, keyword field renamedNT7renamefrom aFinalfalse, keyword fieldCases added to
dataclass6.pyClassCfield(init=)from aFinalfalse, field passed to__init__Cases added to
dataclassKwOnly1.pyDC7field(kw_only=)from aFinaltrue, field passed positionallyCases added to
dataclassFrozen1.pyDC7frozen=from aFinaltrue, field assignedCases added to
dataclassTransform1.pyCustomer4frozen_default=from aFinaltrue, field assignedcreate_model_frozen3frozen_default=whose value isn't staticCases added to
typeNarrowingFalsy1.pyfunc20__bool__returnsLiteral[False], only falsyfunc21__bool__returnsLiteral[False], only falsyfunc22__bool__returnsLiteral[True], only truthyfunc23__bool__returnsbool, eitherfunc24__len__, eitherfunc25__len__, eitherfunc26__len__from a base beforetuplein the MRO, eitherfunc27__len__base aftertuplein the MRO, only truthyfunc28func29__bool__is an instance attribute, only truthyIn
typeNarrowing1.py,maybeis now a non-literalbool, since it was never reassigned and its ternaries now select one branch. IntupleLiteralInference5.py, the ternary inconditional_controlnow has only the selected branch's literal, so appending("",)is an error.Evidence and validation
Commands and configuration:
--type-checker pyright --output concise --old 23aa785c7 --new c9f05ea71, on projects that usesys.platform,sys.version_info,os.nameorTYPE_CHECKINGoutside a plainiforeliftest.srcwith its venv, 5 rounds per build;staticExpression3.py,staticExpression4.pyandstaticExpression5.pywith--pythonplatform Linux, 30 runs per build.Tests and checks run: jest on the tests for every changed sample, the other static condition and TypedDict tests, and every test whose sample uses a namedtuple; prettier, eslint and tsc.
Observed results:
Limitations or unrun checks: Candidates with matches that weren't run, for disk space: bokeh, dd-trace-py, ibis, prefect, rotki, streamlit and zulip.
🤖 AI-assisted validation
Type precision and performance
Static conditions are
Literal[True]orLiteral[False]in any expression, and a ternary whose test is constant has only that branch's type. Types widen only where main's were wrong: aboolnamedTYPE_CHECKINGthat doesn't refer to typing's, which main gaveLiteral[True]when assigned, and the falsy branch for a class object whose metaclass makes it possibly falsy, or for a non-empty tuple subclass whose__bool__or__len__does. A class whose only__bool__is an instance attribute is always truthy, as at runtime.Author responsibility
Read the AI contribution policy and confirm before submitting: