Repository navigation
Fix NewType identity comparisons with base literals - #11491
Rich Chiodo (rchiodo) merged 4 commits into
Conversation
Treat NewType instances as comparable to their underlying base literals in is/narrowing checks so valid runtime comparisons are not marked unreachable. Fixes microsoft#11463
| if (isIsOperator || isNoneInstance(subtype)) { | ||
| const isSubtype = evaluator.assignType(subtype, literalType); | ||
| return isSubtype ? literalType : undefined; | ||
| let compareType: Type = subtype; |
There was a problem hiding this comment.
Copilot generated:
The Skeptic execution-verified that the fix only unwraps one level of NewType. For X = NewType("X", bool) then Y = NewType("Y", X), y is True is still marked unreachable: compareType becomes the inner NewType X, so assignType(X, Literal[True]) is false → returns undefined → dead branch. This is the exact bug class this PR fixes, one level deeper. Either walk the NewType base chain to the ultimate non-NewType base (a loop / shared helper) and add a nested-NewType row to newTypeIsLiteral1.py, or document the single-level limitation explicitly.
[verified]
|
|
||
| const adjustedSubtype = useExpandedSubtype ? subtype : unexpandedSubtype; | ||
|
|
||
| // NewType instances can be identity-compared with their underlying base type. |
There was a problem hiding this comment.
Copilot generated:
The Architect notes this new block re-implements None-detection (isNoneInstance + assignType(..., getNoneType())) that already exists in the original checks ~10 lines below. Preferred direction: unwrap the NewType to its base instance once and let the existing exact-None / potentially-None checks run against it, returning the original NewType subtype on the positive branch — mirroring the cleaner structure the literal-comparison hunk already uses. This collapses two parallel None paths into one.
[verified]
| const baseInstance = ClassType.cloneAsInstance(baseClass); | ||
| if (isNoneInstance(baseInstance)) { | ||
| resultIncludesNoneSubtype = true; | ||
| return isPositiveTest ? adjustedSubtype : undefined; |
There was a problem hiding this comment.
Copilot generated:
[unverified] The Skeptic flagged an identity inconsistency: when the base is NoneType (Apple case), this returns the NewType (adjustedSubtype), but when the base merely contains None (e.g. NewType("Obj", object)), the positive branch returns bare None via addConditionToType(getNoneType(), …) instead of the NewType. This diverges from the literal-comparison path, which always returns the NewType subtype on a positive match. Make this a deliberate decision and add a test either way.
[verified]
| const isSubtype = evaluator.assignType(subtype, literalType); | ||
| return isSubtype ? literalType : undefined; | ||
| let compareType: Type = subtype; | ||
| if (isClassInstance(subtype) && ClassType.isNewTypeClass(subtype) && subtype.shared.baseClasses.length > 0) { |
There was a problem hiding this comment.
Copilot generated:
The Architect, Skeptic, and Advocate all note the NewType-unwrap pattern (isClassInstance(x) && isNewTypeClass(x) && baseClasses.length > 0 → cloneAsInstance(baseClasses[0])) is open-coded in both hunks, with isNewTypeClass checked a third time in this return ternary. Extracting a single getNewTypeBaseInstance(t): ClassType | undefined helper localizes the new dependency on the baseClasses[0] synthesis invariant (createNewType, typeEvaluator.ts:13788) to one place and makes the two hunks obviously symmetric.
[verified]
|
|
||
| const adjustedSubtype = useExpandedSubtype ? subtype : unexpandedSubtype; | ||
|
|
||
| // NewType instances can be identity-compared with their underlying base type. |
There was a problem hiding this comment.
Copilot generated:
Nit (Advocate, structurally confirmed): the new guard line is ~145 columns including indentation, past the repo's printWidth: 120. Prettier will reflow it, so npm run check may bounce until fix:prettier is run. Mechanical — resolve before CI.
[verified]
| Cherry = NewType("Cherry", int) | ||
|
|
||
|
|
||
| def f(a: Apple, b: Banana, c: Cherry) -> None: |
There was a problem hiding this comment.
Copilot generated:
The Advocate flags positive-only coverage. The sample exercises only positive is branches; there is no coverage for the negative branch (b is not True), for a NewType inside a union, for a nested NewType (NewType("Y", X) — see the verified gap above), or the NewType("Obj", object) is None identity case. Adding these would lock in the intended behavior and guard against the residual gaps the reviewers identified.
[verified]
| : adjustedSubtype; | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/typeGuards.ts:1131
The is None fix does not fix its own primary scenario and produces the opposite of correct narrowing. For Apple = NewType("Apple", NoneType), if a is None: should be the reachable branch (Apple), but the positive branch collapses to Never. The first sub-branch returns adjustedSubtype (the NewType instance, a non-None type) while setting resultIncludesNoneSubtype = true; the unchanged post-filter at lines 1152-1156 (isNoneInstance(st) ? st : undefined) then strips that subtype — isNoneInstance is false for a NewType because it lacks the BuiltIn flag — yielding Never. Fix: for the isNoneInstance(baseInstance) case the positive result must be a value the post-filter keeps (a None instance carrying the NewType identity), or skip setting resultIncludesNoneSubtype and return the NewType directly.
[verified]
|
|
||
| def f(a: Apple, b: Banana, c: Cherry) -> None: | ||
| if a is None: | ||
| reveal_type(a, expected_text="Apple") |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/tests/samples/newTypeIsLiteral1.py:12
This assertion is vacuous and hides the functional bug. Because if a is None: is unreachable (see typeGuards.ts:1131), pyright never evaluates reveal_type(a, expected_text="Apple"), so the expected_text check never fires — flipping the literal to expected_text="WRONG_XYZ" still passes with 0 errors. A reveal_type in dead code is not an assertion. Add negative coverage that fails when the branch is unreachable (e.g. a statement after the block that depends on the narrowed binding, or assert the else branch type) so a Never regression can't pass silently.
[verified]
|
|
||
| if (evaluator.assignType(baseInstance, evaluator.getNoneType())) { | ||
| resultIncludesNoneSubtype = true; | ||
| return isPositiveTest |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/typeGuards.ts:1137
For a NewType over a None-compatible non-None base (e.g. ObjNT = NewType("ObjNT", object)), if o is None: narrows to bare None, dropping the ObjNT brand. This is inconsistent with the literal path (line 2773), which deliberately preserves the NewType identity. The behavior mirrors existing base-None narrowing so it may be defensible, but the two newly added paths answer "preserve NewType identity?" differently. Decide the intended behavior, add a test for this path (currently untested), and add a one-line comment explaining the divergence so a future reader doesn't mistake it for a bug.
[verified]
| : adjustedSubtype; | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/typeGuards.ts:1131
The NewType-base unwrap is copy-pasted into two functions (here and lines 2762-2769): identical isClassInstance && isNewTypeClass && baseClasses.length > 0 → baseClasses[0] → isClass() guard → cloneAsInstance. AGENTS.md explicitly calls out this copy/paste-variant pattern. Extract a single getNewTypeBaseInstance(subtype): ClassType | undefined helper so both call sites collapse to one line and there's a single place to evolve depth/Any-base handling.
[verified]
| if (isClass(baseClass)) { | ||
| compareType = ClassType.cloneAsInstance(baseClass); | ||
| } | ||
| } |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/typeGuards.ts:2760
The unwrap is single-level only. NewType's base may itself be a NewType (Y = NewType("Y", X) where X = NewType("X", bool) is legal and instantiable). The patch unwraps one level, so compareType stays a NewType and assignType(X_instance, True) still fails, leaving nested NewType comparisons marked unreachable. Either loop/recurse until the first non-NewType base (natural fit for the suggested shared helper) or explicitly scope nested NewType out with a comment.
[verified]
|
GitHub cannot anchor PR review comments to unchanged lines in the diff. Falling back to a general PR comment for packages/pyright-internal/src/analyzer/typeGuards.ts:L1162. 📍 packages/pyright-internal/src/analyzer/typeGuards.ts:1162 [verified] |
|
The literal-comparison path (bool/int cases) is fixed correctly, but the |
| if (isNewTypeWithSingletonBase(evaluator, adjustedSubtype, evaluator.getNoneType(), isNoneInstance)) { | ||
| resultIncludesNoneSubtype = true; | ||
| return isPositiveTest ? adjustedSubtype : undefined; | ||
| } |
There was a problem hiding this comment.
Negative-branch regression (verified empirically). isNewTypeWithSingletonBase returns true when isExactMatch(base) || assignType(base, target) — i.e. "could the value be the singleton?". That's correct for the positive branch's adjustedSubtype return, but wrong for the negative branch's undefined (eliminate) return. For ObjNT = NewType("ObjNT", object), the base unwraps to object and assignType(object, None) is true, so this block fires and o is not None returns undefined → Never, marking the true branch unreachable (reproduced: reportUnreachable='error' flags the if o is not None: body). In the pre-PR code this case falls through to the assignType(subtype, None) check and correctly keeps the type. Fix: gate the negative-branch elimination on isExactMatch(base) only, so non-singleton bases fall through to the existing exact-/potentially-None checks.
| : subtype; | ||
|
|
||
| if (isNewTypeWithSingletonBase(evaluator, adjustedSubtype, ellipsisType, isEllipsisInstance)) { | ||
| resultIncludesEllipsisSubtype = true; |
There was a problem hiding this comment.
Same negative-branch defect in the ellipsis twin. For an object-based NewType, assignType(object, ellipsisType) is true, so e is not ... returns undefined → Never here too, whereas the existing fall-through at the assignType(subtype, ellipsisType) check would correctly keep the type. Apply the same fix as the is None path (single root cause).
|
|
||
| // Handle type narrowing for expressions of the form "x is None" and "x is not None". | ||
| function narrowTypeForIsNone(evaluator: TypeEvaluator, type: Type, isPositiveTest: boolean) { | ||
| const expandedType = mapSubtypes(type, (subtype) => { |
There was a problem hiding this comment.
The predicate name isNewTypeWithSingletonBase overstates what it checks: for an object base the unwrapped base is not a singleton, yet assignType(object, None) makes it return true. This name is what makes the negative-branch elimination look correct. Consider renaming (e.g. newTypeBaseCouldMatch) and documenting that a true result only justifies keeping a subtype on the positive branch, not eliminating it on the negative branch.
|
|
||
| if d is ...: | ||
| reveal_type(d, expected_text="Dragonfruit") | ||
|
|
There was a problem hiding this comment.
Coverage gap that let the negative-branch regression pass. The sample exercises only positive is branches; there's no is not None / is not ... coverage and no object-based NewType. Add a NewType over a None-compatible non-singleton base (e.g. ObjNT = NewType("ObjNT", object)) and assert that the else of if o is None: (and the body of if o is not None:) stays reachable as ObjNT under reportUnreachable='error', so this class of bug is caught.
|
Core fix for the positive |
|
The core fix works and nested NewTypes are handled correctly. However, there is one real regression: |
Only treat a NewType as the None/ellipsis singleton when its innermost
base is exactly that singleton. A NewType over a merely-compatible base
(e.g. NewType("Obj", object)) now falls through to the generic checks, so
`is not None` / `is not ...` no longer collapse the negative branch to
Never and mark reachable code unreachable.
Replaces the misleadingly-named isNewTypeWithSingletonBase predicate with
the getInnermostNewTypeBaseInstance helper (which now returns undefined for
non-NewTypes), and adds object-based NewType coverage that fails under
reportUnreachable if the negative branch regresses.
Rich Chiodo (rchiodo)
left a comment
There was a problem hiding this comment.
Approved via Review Center.
|
Diff from mypy_primer, showing the effect of this PR on open source code: sympy (https://github.com/sympy/sympy)
- .../projects/sympy/sympy/stats/random_matrix_models.py:111:36 - error: Operator "*" not supported for types "Expr" and "tuple[Unknown, ...] | Unknown | Product | Basic | BooleanFalse | BooleanTrue | Equality | Expr | NaN | One | Zero"
+ .../projects/sympy/sympy/stats/random_matrix_models.py:111:36 - error: Operator "*" not supported for types "Expr" and "tuple[Unknown, ...] | Unknown | Product | Basic | BooleanFalse | BooleanTrue | ComplexInfinity | Equality | Expr | Float | Infinity | Integer | NaN | NegativeInfinity | NegativeOne | Number | One | Rational | Zero"
+ .../projects/sympy/sympy/stats/rv.py:473:25 - error: Argument of type "Expr | Lambda | Zero | One | Integral | Unknown | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | NaN | Piecewise | Basic | NegativeOne | Integer | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | int" cannot be assigned to parameter "args" of type "Expr | complex" in function "__new__"
+ Type "Expr | Lambda | Zero | One | Integral | Unknown | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | NaN | Piecewise | Basic | NegativeOne | Integer | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | int" is not assignable to type "Expr | complex"
- .../projects/sympy/sympy/stats/rv.py:473:25 - error: Argument of type "Expr | Lambda | Zero | One | Integral | Unknown | NegativeOne | Integer | NaN | ComplexInfinity | Rational | Infinity | Number | NegativeInfinity | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | int" cannot be assigned to parameter "args" of type "Expr | complex" in function "__new__"
- Type "Expr | Lambda | Zero | One | Integral | Unknown | NegativeOne | Integer | NaN | ComplexInfinity | Rational | Infinity | Number | NegativeInfinity | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | int" is not assignable to type "Expr | complex"
- Type "Basic" is not assignable to type "Expr | complex"
- "Basic" is not assignable to "Expr"
- "Basic" is not assignable to "complex" (reportArgumentType)
- .../projects/sympy/sympy/stats/rv.py:473:25 - error: Argument of type "Mul | Expr | Lambda | Zero | One | Integral | Unknown | NegativeOne | Integer | NaN | ComplexInfinity | Rational | Infinity | Number | NegativeInfinity | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | int" cannot be assigned to parameter "args" of type "Expr | complex" in function "__new__"
- Type "Mul | Expr | Lambda | Zero | One | Integral | Unknown | NegativeOne | Integer | NaN | ComplexInfinity | Rational | Infinity | Number | NegativeInfinity | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | int" is not assignable to type "Expr | complex"
- .../projects/sympy/sympy/stats/tests/test_discrete_rv.py:138:33 - error: Operator "+" not supported for types "Expr | Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | tuple[Unknown, ...] | MatAdd | int" and "Literal[3]"
+ .../projects/sympy/sympy/stats/tests/test_discrete_rv.py:138:33 - error: Operator "+" not supported for types "Expr | Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | tuple[Unknown, ...] | MatAdd | Infinity | NegativeInfinity | Float | Number | int" and "Literal[3]"
- .../projects/sympy/sympy/stats/tests/test_finite_rv.py:34:23 - error: Operator "/" not supported for types "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | Integer | Lambda | Mul | NegativeOne | Number | Integral | Literal[0]" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | Integer | Lambda | Mul | NegativeOne | Number | Integral | Literal[0]"
+ .../projects/sympy/sympy/stats/tests/test_finite_rv.py:34:23 - error: Operator "/" not supported for types "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | BernoulliDistribution | Probability | Expr | Float | Infinity | NegativeInfinity | NotImplementedType | Lambda | Piecewise | Integral | Literal[0]" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | Integer | Lambda | NegativeOne | Piecewise | Integral | Literal[0]"
- Operator "/" not supported for types "BernoulliDistribution" and "tuple[Unknown, ...]"
- Operator "/" not supported for types "BernoulliDistribution" and "Basic"
+ Operator "/" not supported for types "Literal[0]" and "BernoulliDistribution" (reportOperatorIssue)
+ .../projects/sympy/sympy/stats/tests/test_finite_rv.py:35:23 - error: Operator "*" not supported for types "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | BernoulliDistribution | Probability | Expr | Float | Infinity | NegativeInfinity | NotImplementedType | Lambda | Piecewise | Integral | Literal[0]" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | Integer | Lambda | NegativeOne | Piecewise | Integral | Literal[0]"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "BernoulliDistribution"
+ Operator "*" not supported for types "ComplexInfinity" and "BernoulliDistribution"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "tuple[Unknown, ...]"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "Basic"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "Literal[0]"
- ... (reportOperatorIssue)
- .../projects/sympy/sympy/stats/tests/test_finite_rv.py:35:23 - error: Operator "*" not supported for types "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | Integer | Lambda | Mul | NegativeOne | Number | Integral | Literal[0]" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | Integer | Lambda | Mul | NegativeOne | Number | Integral | Literal[0]"
- Operator "*" not supported for types "BernoulliDistribution" and "Infinity"
+ .../projects/sympy/sympy/stats/tests/test_finite_rv.py:35:23 - error: Operator "/" not supported for types "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType | Expr | int" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | Integer | Lambda | NegativeOne | Piecewise | Integral | Literal[0]"
- .../projects/sympy/sympy/stats/tests/test_finite_rv.py:35:23 - error: Operator "/" not supported for types "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Expr | Infinity | NegativeInfinity | Float | NotImplementedType | tuple[Unknown, ...] | MatMul | int" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | Integer | Lambda | Mul | NegativeOne | Number | Integral | Literal[0]"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "BernoulliDistribution"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "tuple[Unknown, ...]"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "Basic"
- Operator "/" not supported for types "tuple[Unknown, ...]" and "Literal[0]"
- Operator "/" not supported for types "int" and "BernoulliDistribution"
- Operator "/" not supported for types "int" and "tuple[Unknown, ...]"
- Operator "/" not supported for types "int" and "Basic" (reportOperatorIssue)
+ Operator "/" not supported for types "int" and "BernoulliDistribution" (reportOperatorIssue)
- .../projects/sympy/sympy/stats/tests/test_finite_rv.py:470:12 - error: Operator "+" not supported for types "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | Integer | Lambda | Mul | NegativeOne | Number | Integral | Literal[0]" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | Expr | Float | ComplexInfinity | NaN | Rational | Infinity | NegativeInfinity | NotImplementedType | tuple[Unknown, ...] | Sum | ZeroMatrix | Piecewise | Basic | Integer | Lambda | Mul | NegativeOne | Number | Integral | Literal[0]"
+ .../projects/sympy/sympy/stats/tests/test_finite_rv.py:470:12 - error: Operator "+" not supported for types "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | BernoulliDistribution | Probability | Expr | Float | Infinity | NegativeInfinity | NotImplementedType | Lambda | Piecewise | Integral | Literal[0]" and "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | BernoulliDistribution | Probability | Expr | Float | Infinity | NegativeInfinity | NotImplementedType | Lambda | Piecewise | Integral | Literal[0]"
... (truncated 1414 lines) ...
|
|
Thanks for the PR :) |
|
Yipee! :) |
Summary
Fixes pyright treating valid
iscomparisons betweenNewTypeinstances and their underlying base literals as unreachable.Problem
Fix
Compare
NewTypeinstances against their underlying base types when evaluatingisnarrowing for literals andNone.Testing
newTypeIsLiteral1.py+NewType8test (0 errors expected)Fixes #11463