Skip to content

Commit 01e2a8c

Browse files
authored
Use union for captured vars in or pattern (#19710)
Mypy creates a union type for the pattern subject in an or pattern already. Use union for captured variables as well.
1 parent fa7fa7f commit 01e2a8c

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

mypy/checkpattern.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def visit_or_pattern(self, o: OrPattern) -> PatternType:
192192
for capture_list in capture_types.values():
193193
typ = UninhabitedType()
194194
for _, other in capture_list:
195-
typ = join_types(typ, other)
195+
typ = make_simplified_union([typ, other])
196196

197197
captures[capture_list[0][0]] = typ
198198

test-data/unit/check-python310.test

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1204,13 +1204,13 @@ match m:
12041204
case 1 | "foo":
12051205
reveal_type(m) # N: Revealed type is "Union[Literal[1], Literal['foo']]"
12061206

1207-
[case testMatchOrPatterCapturesMissing]
1207+
[case testMatchOrPatternCapturesMissing]
12081208
from typing import List
12091209
m: List[int]
12101210

12111211
match m:
12121212
case [x, y] | list(x): # E: Alternative patterns bind different names
1213-
reveal_type(x) # N: Revealed type is "builtins.object"
1213+
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.list[builtins.int]]"
12141214
reveal_type(y) # N: Revealed type is "builtins.int"
12151215
[builtins fixtures/list.pyi]
12161216

@@ -1219,7 +1219,7 @@ m: object
12191219

12201220
match m:
12211221
case list(x) | dict(x):
1222-
reveal_type(x) # N: Revealed type is "typing.Iterable[Any]"
1222+
reveal_type(x) # N: Revealed type is "Union[builtins.list[Any], builtins.dict[Any, Any]]"
12231223
[builtins fixtures/dict.pyi]
12241224

12251225
-- Interactions --
@@ -1405,7 +1405,7 @@ m: Union[str, bytes, int]
14051405

14061406
match m:
14071407
case str(a) | bytes(a):
1408-
reveal_type(a) # N: Revealed type is "builtins.object"
1408+
reveal_type(a) # N: Revealed type is "Union[builtins.str, builtins.bytes]"
14091409
reveal_type(m) # N: Revealed type is "Union[builtins.str, builtins.bytes]"
14101410
case b:
14111411
reveal_type(b) # N: Revealed type is "builtins.int"

0 commit comments

Comments
 (0)