8000 Introduce temporary named expressions for `match` subjects by sterliakov · Pull Request #18446 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Introduce temporary named expressions for match subjects #18446

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

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Merge remote-tracking branch 'upstream/master' into bugfix/st-synthet…
…ic-named-expr-in-match
  • Loading branch information
sterliakov committed Mar 29, 2025
commit 6e09fd03b8b4415d8df9cdd39d4ea3b817c95164
8 changes: 6 additions & 2 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5533,7 +5533,7 @@ def visit_continue_stmt(self, s: ContinueStmt) -> None:
return

def visit_match_stmt(self, s: MatchStmt) -> None:
named_subject = self._make_named_statement_for_match(s.subject)
named_subject = self._make_named_statement_for_match(s)
with self.binder.frame_context(can_skip=False, fall_through=0):
subject_type = get_proper_type(self.expr_checker.accept(s.subject))

Expand Down Expand Up @@ -5612,8 +5612,9 @@ def visit_match_stmt(self, s: MatchStmt) -> None:
with self.binder.frame_context(can_skip=False, fall_through=2):
pass

def _make_named_statement_for_match(self, subject: Expression) -> Expression:
def _make_named_statement_for_match(self, s: MatchStmt) -> Expression:
"""Construct a fake NameExpr for inference if a match clause is complex."""
subject = s.subject
expressions_to_preserve = (
# Already named - we should infer type of it as given
NameExpr,
Expand All @@ -5634,6 +5635,8 @@ def _make_named_statement_for_match(self, subject: Expression) -> Expression:
)
if isinstance(subject, expressions_to_preserve):
return subject
elif s.subject_dummy is not None:
return s.subject_dummy
else:
# Create a dummy subject expression to handle cases where a match statement's subject
# is not a literal value. This lets us correctly narrow types and check exhaustivity
Expand All @@ -5642,6 +5645,7 @@ def _make_named_statement_for_match(self, subject: Expression) -> Expression:
v = Var(name)
named_subject = NameExpr(name)
named_subject.node = v
s.subject_dummy = named_subject
return named_subject

def _get_recursive_sub_patterns_map(
Expand Down
53 changes: 53 additions & 0 deletions test-data/unit/check-python310.test
Original file line number Diff line number Diff line change
Expand Up @@ -2668,3 +2668,56 @@ match 0:
i # E: Statement is unreachable
case other:
other # E: Statement is unreachable

[case testMatchNamedTupleSequence]
from typing import Any, NamedTuple

class T(NamedTuple):
t: list[Any]

class K(NamedTuple):
k: int

def f(t: T) -> None:
match t:
case T([K() as k]):
reveal_type(k) # N: Revealed type is "Tuple[builtins.int, fallback=__main__.K]"
[builtins fixtures/tuple.pyi]

[case testNewRedefineMatchBasics]
# flags: --allow-redefinition-new --local-partial-types

def f1(x: int | str | list[bytes]) -> None:
match x:
case int():
reveal_type(x) # N: Revealed type is "builtins.int"
case str(y):
reveal_type(y) # N: Revealed type is "builtins.str"
case [y]:
reveal_type(y) # N: Revealed type is "builtins.bytes"
reveal_type(y) # N: Revealed type is "Union[builtins.str, builtins.bytes]"

[case testNewRedefineLoopWithMatch]
# flags: --allow-redefinition-new --local-partial-types

def f1() -> None:
while True:
x = object()
match x:
case str(y):
pass
case int():
pass
if int():
continue

def f2() -> None:
for x in [""]:
match str():
case "a":
y = ""
case "b":
y = 1
return
reveal_type(y) # N: Revealed type is "builtins.str"
[builtins fixtures/list.pyi]
You are viewing a condensed version of this merge commit. You can view the full changes here.
0