Repository navigation
Expand TypeVar subject in sequence and mapping pattern narrowing - #11959
crypt0lith wants to merge 5 commits into
Conversation
getSequencePatternInfo and getMappingPatternInfo run their Sequence and Mapping assignability checks against a TypeVar subject instead of its concrete type, and treat a union bound or constraints as a single non-class subtype, so the patterns are reported as never matched. Expand the TypeVar per subtype, and keep its condition on narrowed tuple and Sequence types. Fixes microsoft#10689
|
Looks good. The TypeVar condition is now retained, and the merge with Non-blocking follow-up (pre-existing on class Pair(tuple[int, int]):
def marker(self) -> None: ...
TPair = TypeVar("TPair", bound=Pair)
def generic_pair(value: TPair) -> TPair:
match value:
case (first, second):
value.marker() # still reportAttributeAccessIssue; narrowed to tuple[int, int]*
return value
case _:
return valueIf it's easy to preserve the bound subclass here, adding it to this PR would be nice. Otherwise it can be a follow-up. 🤖 AI-assisted review posted on behalf of Bill Schnurr (@bschnurr). |
Rich Chiodo (rchiodo)
left a comment
There was a problem hiding this comment.
There's a pre-existing negative-path case that the new positive narrowing exposes:
from typing import Literal, TypedDict, TypeVar, assert_never
class A(TypedDict):
kind: Literal['a']
x: int
class B(TypedDict):
kind: Literal['b']
y: str
TAB = TypeVar('TAB', bound=A | B)
def generic(x: TAB) -> TAB:
match x:
case {'kind': 'a'}: return x
case {'kind': 'b'}: return x
case _: assert_never(x)
def concrete(x: A | B) -> A | B:
match x:
case {'kind': 'a'}: return x
case {'kind': 'b'}: return x
case _: assert_never(x)Both revisions report an error at assert_never in generic because the wildcard retains TAB. The concrete union is exhaustive. On 72bb148, the positive cases narrow to A* and B*; base treated them as unreachable. Could the negative matching path expand the bound too, with an exhaustiveness test? I haven't tested that change.
There's also a possible scaling issue in getNarrowedSubtypes. It filters and recombines all entries and concretizes the whole TypeVar again for each entry of the same TypeVar. With N conditioned literal subtypes, the literal-map fast path is bypassed, so repeated union construction looks like it can do roughly cubic work. The tuple-expansion cap comes later.
The stress case used a TypeVar bound to 100 distinct string literals, with tuple, starred-list and one-element sequence cases plus a wildcard. Shared-host runs looked substantially slower, but they were contended. The performance impact is inconclusive, and there's no clean benchmark or defensible number. Would grouping or caching entries once per TypeVar help, or could we run an uncontended scaling test? I haven't tested the grouping or caching idea.
The existing tests already cover constrained int/str and other sequence-plus-class exhaustion, but a few additional controls might be useful:
- Returning an unrelated
TwhereUis expected should still error after narrowing. - Standalone TypeVars bounded to
strorbytesshould still never match sequence patterns. - Exhaustion across different tuple arities, or a starred-list case followed by a
strcase.
7c98fe9 to
d4e5506
Compare
|
The repeated union construction in #11959 (review) is cached per TypeVar in 16a90cb. The exhaustiveness case in #11959 (review) and the tuple subclass case in #11959 (comment) are fixed in d4e5506. |
🟢 Pyright CLI QA —
|
Bill Schnurr (bschnurr)
left a comment
There was a problem hiding this comment.
The current per-TypeVar cache addresses the repeated recombination in my earlier review. One remaining performance question is that getNarrowedSubtypes still filters all entries once per distinct TypeVar, so grouping costs O(k*n) for k TypeVars and n expanded entries.
I compared the base and this head with five alternating runs of a single TypeVar bound to 512 literals. Median checker time was 0.84s versus 0.88s; the shared host had substantial wall-time outliers. This does not establish a performance regression or measure the distinct-TypeVar case. Could we check that scaling, alongside the pending benchmark, before deciding whether one-pass grouping is needed?
I also replayed the earlier NotRequired QA cases: the matched-key false positives are gone, and the missing-key negative control still reports an error. The evaluator suite passed on this head.
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
|
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
|
|
Bill Schnurr (@bschnurr) Each distinct TypeVar contributes at least one expanded entry, so pyright/packages/pyright-internal/src/analyzer/types.ts Lines 4397 to 4400 in c5c7e81 Grouping in one pass wouldn't change the overall bound. The benchmark on c5c7e81 found no regressions; every time delta is within +3.2%: #11959 (comment) |
Summary
Fixes #10689
Sequence and mapping patterns on a TypeVar subject are reported as never matched when the TypeVar has no bound, is bound to
Anyor to a union, or is constrained. Narrowing a TypeVar subject to a tuple also yields a tuple type that isn't assignable back to the TypeVar.Root cause
getSequencePatternInfoandgetMappingPatternInfomake each subtype concrete, but their fallback subtype and supertype checks againstSequenceandMappingreceive the TypeVar instead of its concrete type, and reject it.narrowTypeBasedOnSequencePatternbuilds the narrowed tuple andSequencetypes without the TypeVar's condition.Fix
NotRequiredentries marked provided.Sequencetypes, building it from the TypeVar when its concrete type isAny.Test
Cases added to
matchUnnecessary1.pyfunc6func7func8func9Anyfunc10intfunc11intandstrCases added to
matchSequence1.pytest_typevar_subjectSequence, unmatched keeps TypeVartest_any_bound_typevar_subjectAnybound narrows to conditionedSequence[Any]test_tuple_bound_typevar_subjecttest_union_bound_typevar_subjecttest_constrained_typevar_subjectCases added to
matchSequence3.pyfunc5func6Cases added to
matchMapping1.pytest_typevar_subjecttest_union_bound_typevar_subjectMappingmember, unmatched keeps TypeVartest_union_bound_typevar_subject_expand_entry**rest-only pattern leaves non-mapping membertest_union_bound_typevar_negative_narrowingtest_union_bound_typevar_negative_exhaustiontest_union_bound_typevar_not_required_narrowingNotRequiredkey accessible after narrowing union boundtest_union_bound_typevar_not_required_accessNotRequiredkey not accessible after narrowing union boundCases added to
matchExhaustion1.pyfunc12func13Expected error counts changed:
MatchUnnecessary1(7 -> 11),MatchSequence3(1 -> 2)