Skip to content

Commit 9ee7b8a

Browse files
TH3CHARLieilevkivskyi
authored andcommitted
Fix error when assigning a ternary with an empty collection to a union type variable (#7892)
resolves #7780
1 parent 24b7dba commit 9ee7b8a

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

mypy/checkexpr.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3534,9 +3534,11 @@ def visit_conditional_expr(self, e: ConditionalExpr) -> Type:
35343534

35353535
if_type = self.analyze_cond_branch(if_map, e.if_expr, context=ctx)
35363536

3537+
# Analyze the right branch using full type context and store the type
3538+
full_context_else_type = self.analyze_cond_branch(else_map, e.else_expr, context=ctx)
35373539
if not mypy.checker.is_valid_inferred_type(if_type):
35383540
# Analyze the right branch disregarding the left branch.
3539-
else_type = self.analyze_cond_branch(else_map, e.else_expr, context=ctx)
3541+
else_type = full_context_else_type
35403542

35413543
# If it would make a difference, re-analyze the left
35423544
# branch using the right branch's type as context.
@@ -3556,7 +3558,7 @@ def visit_conditional_expr(self, e: ConditionalExpr) -> Type:
35563558
#
35573559
# TODO: Always create a union or at least in more cases?
35583560
if isinstance(get_proper_type(self.type_context[-1]), UnionType):
3559-
res = make_simplified_union([if_type, else_type])
3561+
res = make_simplified_union([if_type, full_context_else_type])
35603562
else:
35613563
res = join.join_types(if_type, else_type)
35623564

test-data/unit/check-unions.test

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1004,3 +1004,12 @@ do_thing_with_enums(boop) # E: Argument 1 to "do_thing_with_enums" has incompat
10041004
# N: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance \
10051005
# N: Consider using "Sequence" instead, which is covariant
10061006
[builtins fixtures/isinstancelist.pyi]
1007+
1008+
[case testAssignUnionWithTenaryExprWithEmptyCollection]
1009+
from typing import Dict, List, Union
1010+
x: Union[int, List[int]] = 1 if bool() else []
1011+
y: Union[int, Dict[int, int]] = 1 if bool() else {}
1012+
1013+
u: Union[int, List[int]] = [] if bool() else 1
1014+
v: Union[int, Dict[int, int]] = {} if bool() else 1
1015+
[builtins fixtures/isinstancelist.pyi]

0 commit comments

Comments
 (0)