Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix incorrect "Incompatible types in capture pattern" error for narrowed types #18155

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
analyze_member_access,
type_object_type,
)
from mypy.checkpattern import PatternChecker
from mypy.checkpattern import PatternChecker, PatternType
from mypy.constraints import SUPERTYPE_OF
from mypy.erasetype import erase_type, erase_typevars, remove_instance_last_known_values
from mypy.errorcodes import TYPE_VAR, UNUSED_AWAITABLE, UNUSED_COROUTINE, ErrorCode
Expand Down Expand Up @@ -5296,7 +5296,20 @@ def visit_match_stmt(self, s: MatchStmt) -> None:
# capture variable may depend on multiple patterns (it
# will be a union of all capture types). This pass ignores
# guard expressions.
pattern_types = [self.pattern_checker.accept(p, subject_type) for p in s.patterns]
pattern_types: list[PatternType] = []
type_context = subject_type
for p in s.patterns:
pattern_type = self.pattern_checker.accept(p, type_context)
pattern_types.append(pattern_type)
new_type_context = get_proper_type(pattern_type.rest_type)
if isinstance(new_type_context, UninhabitedType):
continue
if isinstance(new_type_context, UnionType) and any(
isinstance(get_proper_type(t), UninhabitedType) for t in new_type_context.items
):
continue
type_context = new_type_context

type_maps: list[TypeMap] = [t.captures for t in pattern_types]
inferred_types = self.infer_variable_types_from_type_maps(type_maps)

Expand Down
12 changes: 11 additions & 1 deletion test-data/unit/check-python310.test
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ match m:
case a:
reveal_type(a) # N: Revealed type is "__main__.A"

[case testMatchCapturePatternNarrows]
x: int | None
y: int

match x:
case None:
pass
case y:
reveal_type(y) # N: Revealed type is "builtins.int"

-- Literal Pattern --

[case testMatchLiteralPatternNarrows]
Expand Down Expand Up @@ -1466,7 +1476,7 @@ m3: Tuple[Union[int, str]]
match m3:
case (1,):
reveal_type(m3) # N: Revealed type is "Tuple[Literal[1]]"
case r2:
case r3:
reveal_type(m3) # N: Revealed type is "Tuple[Union[builtins.int, builtins.str]]"

m4: Tuple[Literal[1], int]
Expand Down
Loading