Repository navigation
Fix generic NamedTuple match narrowing for bounded type vars - #11489
Rich Chiodo (rchiodo) merged 5 commits into
Conversation
When matching a generic NamedTuple class pattern against object, unsolved type variables with bounds (e.g. T: bool) are now specialized using their bound types instead of Unknown or bare type parameters. Fixes microsoft#11487
|
|
||
| // Use the default value if there is one. | ||
| if (typeVar.shared.isDefaultExplicit && !this._options.replaceUnsolved?.useUnknown) { | ||
| return this._solveDefaultType(typeVar, recursionCount); |
There was a problem hiding this comment.
Copilot generated:
Global blast radius (High). All three non-rule reviewers independently flagged this: ApplySolvedTypeVarsTransformer.transformTypeVar is the central specialization engine, called from ~31 sites across 9 files. This unconditional unsolved-bounded-TypeVar→bound block fires for every replaceUnsolved caller, not just pattern matching — the Skeptic verified that first([]) (with T: bool) infers Unknown today and would now become its bound engine-wide. The comment even admits the motive is pattern-matching-specific. Localize this: add an opt-in flag on replaceUnsolved (e.g. useBoundForUnsolved) and thread it from the pattern-matching path (patternMatching.ts:1012) rather than changing the default for all callers. This is an upstream-owned subrepo requiring surgical diffs.
[verified]
|
|
||
| // Use the default value if there is one. | ||
| if (typeVar.shared.isDefaultExplicit && !this._options.replaceUnsolved?.useUnknown) { | ||
| return this._solveDefaultType(typeVar, recursionCount); |
There was a problem hiding this comment.
Copilot generated:
Missing useUnknown guard (High). The Advocate and Skeptic both note the existing default-type branch at line 4291 is guarded by && !this._options.replaceUnsolved?.useUnknown, but this new bound block has no such guard and sits right before the final return. A caller that explicitly passes replaceUnsolved.useUnknown = true (the "force Unknown" path, e.g. specializeWithUnknownTypeArgs consumers) would now silently receive bounds instead — overriding documented caller intent. Gate this block with && !this._options.replaceUnsolved?.useUnknown.
[verified]
| if (!this._shouldReplaceTypeVar(typeVar)) { | ||
| return undefined; | ||
| } | ||
|
|
There was a problem hiding this comment.
Copilot generated:
Solved-to-Unknown→bound changes error-recovery inference globally (Medium). The Skeptic verified this keys on isUnknown (not isAny), so Any propagation is correctly preserved — good. But a bounded TypeVar genuinely solved to Unknown (e.g. an argument sourced from an unresolved import / error type) will now snap to its bound across the whole evaluator, changing gradual/error-recovery behavior. Same fix as above: gate behind the pattern-match-specific option rather than the global transformer.
[verified]
| let exprType = evaluator.getTypeOfExpression(pattern.d.className, EvalFlags.CallBaseDefaults).type; | ||
|
|
||
| // If this is a class (but not a type alias that refers to a class), | ||
| // specialize it with Unknown type arguments. |
There was a problem hiding this comment.
Copilot generated:
Untested edge case: positional generic NamedTuple match (Medium). The Skeptic verified selfSpecializeClass (typeUtils.ts:1166-1184) does NOT receive getTupleClassType() and uses cloneAsBound, whereas the replaced specializeWithUnknownTypeArgs(exprType, evaluator.getTupleClassType()) specifically threaded the tuple class type. For a NamedTuple, positional matching (case Thing(x):) relies on tuple structure via __match_args__. The sample only tests case Thing() with attribute access, so a positional-match regression here would be silent. Add a positional-match sample to confirm this path still works.
[verified]
| if (!this._shouldReplaceTypeVar(typeVar)) { | ||
| return undefined; | ||
| } | ||
|
|
There was a problem hiding this comment.
Copilot generated:
Introduced duplication (Architect, High). The bound-conversion ternary TypeBase.isInstantiable(x) ? convertToInstantiable(x.shared.boundType, /* includeSubclasses */ false) : convertToInstance(x.shared.boundType) appears 3× (two here, one in patternMatching.ts). Extract a single getBoundTypeForTypeVar(typeVar) helper. The predicate typeParams.some(p => isTypeVar(p) && p.shared.boundType) is also duplicated 2× in patternMatching.ts.
[verified]
| scopeIds: getTypeVarScopeIds(unexpandedSubtype), | ||
| tupleClassType: evaluator.getTupleClassType(), | ||
| }, | ||
| } |
There was a problem hiding this comment.
Copilot generated:
This block clobbers correctly-solved type args (Medium). The Skeptic showed resultType is first computed by solveAndApplyConstraints (lines 1012-1022), then unconditionally overwritten whenever any param has a bound. Solved args are discarded — e.g. a subject Thing[Literal[True]] matched by case Thing(): widens to the bound bool; and unbounded params in the same class get substituted with getUnknownForTypeVar even when they were solved. This is an untested narrowing regression and is likely redundant with the typeUtils change (constraint solving already routes through replaceUnsolved). Either drop this block, or only fill the bound for params that remained unsolved while preserving solved args.
[verified]
| scopeIds: getTypeVarScopeIds(unexpandedSubtype), | ||
| tupleClassType: evaluator.getTupleClassType(), | ||
| }, | ||
| } |
There was a problem hiding this comment.
Copilot generated:
Shotgun-fix consolidation (High). All three reviewers note there are three overlapping mechanisms implementing the same "use the bound" idea: (1) the early selfSpecializeClass, (2) this post-match override, and (3) the global typeUtils transformer. The Advocate recommends a concrete experiment: revert both typeUtils hunks, keep only the patternMatching changes, and run NamedTuple12 + MatchClass1; if green, the global edits are unnecessary. Prove the single minimal load-bearing site and delete the others before merge.
[verified]
| if (isClass(exprType) && !exprType.props?.typeAliasInfo) { | ||
| exprType = ClassType.cloneRemoveTypePromotions(exprType); | ||
| exprType = specializeWithUnknownTypeArgs(exprType, evaluator.getTupleClassType()); | ||
| if ( |
There was a problem hiding this comment.
Copilot generated:
The Architect flags useBoundTypeVars as a naming trap: verified at typeUtils.ts:1166-1185/:210-217, it does NOT mean the TypeVar's boundType — it calls TypeVarType.cloneAsBound (the scope-bound-vs-free distinction), filling args with T@Thing, not bool. The actual T→bool substitution happens later in the typeUtils transformer. Two different meanings of "bound" collide in one fix. Add a short comment clarifying this so a future reader doesn't misread the intent.
[verified]
| let exprType = evaluator.getTypeOfExpression(pattern.d.className, EvalFlags.CallBaseDefaults).type; | ||
|
|
||
| // If this is a class (but not a type alias that refers to a class), | ||
| // specialize it with Unknown type arguments. |
There was a problem hiding this comment.
Copilot generated:
Implicit coupling (Architect, Low). The early selfSpecializeClass(... useBoundTypeVars ...) only produces the correct result because the typeUtils transformer later rewrites unsolved bounded vars to their bound. Neither side documents the dependency — altering one silently regresses the other (action-at-a-distance). If both edits are kept, add a comment noting this contract.
[verified]
| TestUtils.validateResults(analysisResults, 3); | ||
| }); | ||
|
|
||
| test('NamedTuple12', () => { |
There was a problem hiding this comment.
Copilot generated:
Validation depth below blast radius (High, raised by all). The PR ran only NamedTuple12 + MatchClass1, but the typeUtils edits touch the hottest substitution routine in the evaluator. Run the full typeEvaluator1..8 suites and review sample-snapshot deltas before merge. If the global change is kept, add a test that pins an unsolved bounded TypeVar outside pattern matching (e.g. first([])) to its intended result, plus coverage for constrained TypeVars (T: (int, str), which use shared.constraints not shared.boundType and currently fall through to Unknown) and instantiable bounded params.
[verified]
|
The core fix is reasonable, but it spreads across three overlapping mechanisms and pushes pattern-matching-specific policy into the shared, upstream-owned ApplySolvedTypeVarsTransformer. Please scope the bound-fallback to the pattern-matching path, avoid unconditionally discarding the constraint-solved resultType, and run the full typeEvaluator* suite to confirm no regressions before merge. |
|
The core fix is right to target generic NamedTuple match narrowing, but it spreads across four overlapping mechanisms — two of which are global edits to the shared |
|
The targeted |
|
The core fix is well-targeted at the pattern-matching path, but it leaks feature-specific policy into shared infrastructure (typeUtils.ts) and layers multiple overlapping mechanisms. Please scope the bound-fallback to the pattern-matching caller (or revert the typeUtils.ts changes if patternMatching.ts alone fixes the sample), avoid widening concretely-solved type args, and consolidate the duplicated bound-projection idiom. Given packages/pyright is an upstream-owned subrepo, keeping the fix localized to pattern matching is strongly preferred. |
| partiallySpecializeType, | ||
| preserveUnknown, | ||
| requiresSpecialization, | ||
| selfSpecializeClass, |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/patternMatching.ts:71
convertToInstantiable and selfSpecializeClass are added to the import list but referenced nowhere in the change. The repo enforces @typescript-eslint/no-unused-vars: "error", so npm run check will fail and block merge. Remove both imports. Their presence suggests an abandoned selfSpecializeClass-based approach — worth confirming that path wasn't the intended cleaner fix.
| return evaluator.mapSubtypesExpandTypeVars( | ||
| type, | ||
| /* options */ undefined, | ||
| (subjectSubtypeExpanded, subjectSubtypeUnexpanded) => { |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/patternMatching.ts:923
The mapSubtypesExpandTypeVars(...) call was rewrapped across multiple lines and the arrow (subjectSubtypeExpanded, subjectSubtypeUnexpanded) => { moved to a deeper nesting level, but the large callback body keeps its prior indentation rather than being re-indented one level inside the arrow. As written this will fail npm run check:prettier. Run npx prettier --write on the file before merge.
| ); | ||
| } | ||
|
|
||
| // Are there any positional arguments? If so, try to get the mappings for |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/patternMatching.ts:1030
Block A (inserted right after resultType = solveAndApplyConstraints(...)) appears to be dead code. When it runs, control falls through to Block B (added after the if/else-if/else), whose guard isClassInstance(resultType) && isInstantiableClass(unexpandedSubtype) && <bounded> is a superset of A's post-state — so B always recomputes resultType and discards A's result. The two blocks have also already drifted: B adds a containsAnyOrUnknown(arg, /* recurse */ true) gate that A lacks. Per AGENTS.md "avoid copy/paste variants", delete Block A and extract Block B into a single helper, e.g. specializeBoundedMatchTypeParams(matchType, subjectTypeArgs, solvedTypeArgs, condition). Confirm NamedTuple12 still passes after deleting A.
| if (isMatchValid) { | ||
| return resultType; | ||
| } | ||
| } |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/patternMatching.ts:1102
Potential subclass-narrowing regression. This block runs for ALL class patterns with a bounded-generic pattern class, not just NamedTuple, and there is no return before it on the exact-match branch. So for a subject that is a subclass of a bounded-generic pattern class (e.g. class Sub(Base[bool]) matched against case Base() where class Base[T: bool]), resultType (the subclass) is rebuilt from unexpandedSubtype (the base), potentially clobbering the narrowed subclass type. Add a subclass test case and either gate this block to the synthesized-pattern (else if) path, or skip it when resultType is a proper subtype of the pattern class.
| reveal_type(value.foo, expected_text="bool") | ||
| return "thing" | ||
| case _: | ||
| return "" |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/tests/samples/matchNamedTupleGeneric1.py:6
Test coverage is limited to a final bound (bool, which cannot be subclassed so T ≡ bool) — the degenerate case. Add coverage for: (1) a non-final bound (T: SomeBase) where narrowing-to-bound is an actual widening — the more interesting correctness case; (2) a subclass subject (see the clobbering concern in patternMatching.ts); and (3) optionally a constrained TypeVar (T: (int, str)), which currently still resolves to Unknown. As written, the suite would stay green even if the subclass regression ships.
|
The core narrowing fix looks correct for the |
Address review feedback on generic NamedTuple match narrowing: - Remove the unused convertToInstantiable / selfSpecializeClass imports that broke `npm run check` (no-unused-vars). - Delete the dead/duplicated bound-fallback block and extract the remaining logic into a single specializeBoundedMatchTypeParams helper. - Gate the fallback with isSameGenericClass so it only fills bounds for the pattern class itself; a subject narrowed to a proper subclass keeps its own type arguments instead of being rebuilt from the widened base class. - Restore the original mapSubtypesExpandTypeVars callback signature (drops the now-unused parameter and the Prettier reflow). - Extend matchNamedTupleGeneric1 with a non-final bound (Animal) and a subclass-subject case that guards against the clobbering regression.
| if ( | ||
| specializedArg && | ||
| !requiresSpecialization(specializedArg) && | ||
| !containsAnyOrUnknown(specializedArg, /* recurse */ true) |
There was a problem hiding this comment.
New narrowing regression. The keep-guard !requiresSpecialization(specializedArg) over-widens a solved-to-TypeVar arg. requiresSpecialization returns true for any bare in-scope TypeVar, so for a subject from a generic context — e.g. def f[S: bool](value: Thing[S]) matched by case Thing() — specializedArg = S fails the keep-branch and the helper returns convertToInstance(param.shared.boundType) = bool, silently replacing the legitimately-narrowed S with its bound. This applies to every bounded-generic class (not just NamedTuple) and has zero test coverage. Trigger replacement on genuine Unknown only — e.g. if (specializedArg && !containsAnyOrUnknown(specializedArg, /* recurse */ true)) return specializedArg; (drop the requiresSpecialization term) — and add a generic-function sample asserting expected_text="S@f".
| reveal_type(value.foo, expected_text="bool") | ||
| return "thing" if value.foo else "" | ||
| case _: | ||
| return "" |
There was a problem hiding this comment.
Positional-match coverage gap. Every sample uses only case Thing() / keyword case Thing(foo=True) / case Container(). Add a positional case Thing(x) / case Container(x) sample to confirm __match_args__ binding still works for generic NamedTuples — a positional regression would otherwise ship silently.
|
Core fix is sound, but the |
|
The new |
| isInstantiableClass(unexpandedSubtype) && | ||
| ClassType.isSameGenericClass(resultType, ClassType.cloneAsInstance(unexpandedSubtype)) && | ||
| unexpandedSubtype.shared.typeParams.some( | ||
| (param) => isTypeVar(param) && param.shared.boundType |
There was a problem hiding this comment.
Sync↔async parity follow-up. The Pylance async copy of narrowTypeBasedOnClassPattern (packages/pylance-internal/src/analyzer/patternMatching.ts) is untouched, so the Pylance async product path (enableAsyncProgram=true) won't get this fix. Deferral is acceptable for an upstream-pyright-targeted PR, but track it as an explicit follow-up to mirror the fix and add Pylance-harness coverage, per the repo's sync↔async parity policy.
|
Main blocker: the bounded-fallback helper should only replace genuine Unknown, not any arg that |
| condition: ReturnType<typeof getTypeCondition> | ||
| ): Type { | ||
| const typeArgs = matchType.shared.typeParams.map((param, index) => { | ||
| const specializedArg = subjectTypeArgs?.[index] ?? solvedTypeArgs?.[index]; |
There was a problem hiding this comment.
📍 packages/pyright-internal/src/analyzer/patternMatching.ts:759
New narrowing regression (High). specializedArg = subjectTypeArgs?.[index] ?? solvedTypeArgs?.[index] indexes subjectTypeArgs by the pattern class's typeParams, but subjectTypeArgs is sourced at the call site from subjectSubtypeExpanded.priv.typeArgs — which may be a different generic class. The Skeptic traced this and I confirmed it against the Branch-2 path (L982–1024): for subject Base[int] matched by case Thing() where class Thing[T: bool](Base[int]), the block fires (guard only relates resultType to unexpandedSubtype, never to the subject), and Base.U=int is misread as Thing.T, narrowing value.foo to int instead of the bound bool. This affects every bounded-generic class with a generic supertype and has zero coverage. Drop the subjectTypeArgs source and rely solely on resultType.priv.typeArgs (which the guard already aligns to the pattern class — it is redundant in Branch 1 and undefined for object subjects, so nothing covered is lost), and add a generic-supertype sample pinning the bound.
[verified]
| // Keep an argument unless it is genuinely Unknown. A bare in-scope TypeVar | ||
| // (e.g. a subject `Thing[S]` from a generic function `def f[S: bool]`) is a | ||
| // legitimately narrowed argument and must not be widened to the bound. | ||
| if (specializedArg && !containsAnyOrUnknown(specializedArg, /* recurse */ true)) { |
There was a problem hiding this comment.
The keep-guard !containsAnyOrUnknown(specializedArg, /* recurse */ true) can over-widen a structurally-known arg that merely contains a nested Unknown. For a subject Box[list] where class Box[T: Sequence[int]] (list == list[Unknown]), resultType is Box[list[Unknown]]; with recurse: true the walker descends into list's arg, finds Unknown, discards the arg, and widens it to the bound Sequence[int] — silently losing the user-written list structure (pre-PR this returned the subject as-is). All current samples use T: bool (no nested structure), so this is uncovered. Consider recurse: false (top-level and union-member Unknown are still detected, so the object-subject and union cases still widen correctly), or gate the block to fire only when at least one arg is genuinely unsolved/Unknown — and add a container-bounded sample pinning the behavior.
|
Looks solid overall and the generic-supertype case is already guarded and tested. One non-blocking note inline about the keep-guard potentially over-widening container-bounded type params with nested Unknown. |
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/solvers/tests/test_solvers.py:1216:18 - error: Operator "+" not supported for types "Basic" and "Expr" (reportOperatorIssue)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:315:25 - error: "Set" is not iterable
+ "__iter__" method not defined (reportGeneralTypeIssues)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:315:25 - error: "ConditionSet" is not iterable
+ "__iter__" method not defined (reportGeneralTypeIssues)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2030:20 - error: "__getitem__" method not defined on type "Basic" (reportIndexIssue)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2042:20 - error: "__getitem__" method not defined on type "Basic" (reportIndexIssue)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2055:20 - error: "__getitem__" method not defined on type "Basic" (reportIndexIssue)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2076:16 - error: Argument of type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+ Type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" is not assignable to type "Sized"
+ "Set" is incompatible with protocol "Sized"
+ "__len__" is not present (reportArgumentType)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2077:20 - error: "__getitem__" method not defined on type "Basic" (reportIndexIssue)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2270:16 - error: Argument of type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+ Type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" is not assignable to type "Sized"
+ "Set" is incompatible with protocol "Sized"
+ "__len__" is not present (reportArgumentType)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2351:16 - error: Argument of type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+ Type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" is not assignable to type "Sized"
+ "Set" is incompatible with protocol "Sized"
+ "__len__" is not present (reportArgumentType)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2364:16 - error: Argument of type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+ Type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" is not assignable to type "Sized"
+ "Set" is incompatible with protocol "Sized"
+ "__len__" is not present (reportArgumentType)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2370:16 - error: Argument of type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+ Type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" is not assignable to type "Sized"
+ "Set" is incompatible with protocol "Sized"
+ "__len__" is not present (reportArgumentType)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2538:16 - error: Argument of type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+ Type "Unknown | FiniteSet | Set | Intersection | Union | Complement | Any | ConditionSet" is not assignable to type "Sized"
+ "Set" is incompatible with protocol "Sized"
+ "__len__" is not present (reportArgumentType)
+ .../projects/sympy/sympy/solvers/tests/test_solveset.py:2541:20 - error: Argument of type "Unknown | Basic | Any" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+ Type "Unknown | Basic | Any" is not assignable to type "Sized"
+ "Basic" is incompatible with protocol "Sized"
+ "__len__" is not present (reportArgumentType)
+ .../projects/sympy/sympy/stats/symbolic_probability.py:75:9 - error: Method "doit" overrides class "Basic" in an incompatible manner
+ Return type mismatch: base method returns type "Basic", override returns type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]"
+ Type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]" is not assignable to type "Basic"
+ "Literal[0]" is not assignable to "Basic" (reportIncompatibleMethodOverride)
+ .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1543:12 - error: No overloads for "simplify" match the provided arguments (reportCallIssue)
+ .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1543:21 - error: Argument of type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]" cannot be assigned to parameter "expr" of type "Basic" in function "simplify"
+ Type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]" is not assignable to type "Basic"
+ "Literal[0]" is not assignable to "Basic" (reportArgumentType)
+ .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1545:12 - error: No overloads for "simplify" match the provided arguments (reportCallIssue)
+ .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1545:21 - error: Argument of type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]" cannot be assigned to parameter "expr" of type "Basic" in function "simplify"
+ Type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]" is not assignable to type "Basic"
+ "Literal[0]" is not assignable to "Basic" (reportArgumentType)
+ .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1550:12 - error: No overloads for "simplify" match the provided arguments (reportCallIssue)
+ .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1550:21 - error: Argument of type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]" cannot be assigned to parameter "expr" of type "Basic" in function "simplify"
+ Type "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]" is not assignable to type "Basic"
+ "Literal[0]" is not assignable to "Basic" (reportArgumentType)
- .../projects/sympy/sympy/stats/tests/test_discrete_rv.py:41:12 - error: Operator "-" not supported for types "Unknown | Expr | tuple[Unknown, ...] | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | Literal[0]" and "Unknown | Expr | MatrixExpr | One | NegativeOne | Zero | Integer | int"
+ .../projects/sympy/sympy/stats/tests/test_discrete_rv.py:41:12 - error: Operator "-" not supported for types "Unknown | Expr | tuple[Unknown, ...] | Sum | ZeroMatrix | Zero | NaN | Piecewise | Basic | Literal[0]" and "Unknown | Expr | MatrixExpr | One | NegativeOne | Zero | Integer | int"
- .../projects/sympy/sympy/stats/tests/test_discrete_rv.py:41:37 - error: Operator "**" not supported for types "Unknown | Expr | tuple[Unknown, ...] | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | Literal[0]" and "Literal[2]"
+ .../projects/sympy/sympy/stats/tests/test_discrete_rv.py:41:37 - error: Operator "**" not supported for types "Unknown | Expr | tuple[Unknown, ...] | Sum | ZeroMatrix | Zero | NaN | Piecewise | Basic | Literal[0]" and "Literal[2]"
- .../projects/sympy/sympy/stats/tests/test_discrete_rv.py:85:12 - error: Operator "-" not supported for types "Expr | Unknown | tuple[Unknown, ...] | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | Literal[0]" and "Expr | Unknown | MatrixExpr | One | NegativeOne | Zero | Integer | int"
... (truncated 368 lines) ...
|
|
Thanks for the PR |
PR #11489 added a fallback that specializes unsolved bounded type parameters to their bound after a class pattern match. The guard that distinguishes a solved argument from an unsolved one used containsAnyOrUnknown(arg, recurse=true), which descends into type arguments. As a result a concrete-but-implicitly-parameterized argument (bare list = list[Unknown], dict, set, list[Any]) was misclassified as unsolved and widened to the parameter's bound, breaking previously valid code (issue #11526). Only treat a bare top-level Unknown - the constraint solver's unsolved sentinel - as needing the bound fallback, so concrete arguments are preserved. Fixes #11526 Co-authored-by: Copilot <[email protected]>
Summary
Fixes pyright incorrectly reporting
Unknownfor fields on genericNamedTupleclasses after a successful class pattern match when the type parameter has a bound (e.g.Thing[T: bool]).Problem
Fix
Unknownfor bounded type paramsobject, specialize bounded type params to their boundsUnknownTesting
matchNamedTupleGeneric1.py+NamedTuple12testnpm run test:norebuild -- --testNamePattern=NamedTuple12passesMatchClass1regression test passesFixes #11487