Skip to content

Commit 85e4aa8

Browse files
committed
Force list expression to infer Union type of member types.
1 parent ec4ccb0 commit 85e4aa8

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

mypy/checkexpr.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5029,12 +5029,39 @@ def fast_container_type(
50295029
self.resolved_type[e] = ct
50305030
return ct
50315031

5032+
def infer_item_type(self, item_types: List[Type]) -> Type:
5033+
"""Infer the item type for a list based on its elements."""
5034+
joined_type = self.chk.join_types(*item_types)
5035+
proper_joined = get_proper_type(joined_type)
5036+
if (
5037+
isinstance(proper_joined, Instance)
5038+
and proper_joined.type.fullname == "builtins.object"
5039+
and len(set(map(type, item_types))) > 1
5040+
):
5041+
# if we can't find a common supertype other than 'object',
5042+
# use a Union of the item types
5043+
return UnionType.make_simplified_union(item_types)
5044+
else:
5045+
# otherwise just use the common supertype
5046+
return joined_type
5047+
50325048
def check_lst_expr(self, e: ListExpr | SetExpr | TupleExpr, fullname: str, tag: str) -> Type:
50335049
# fast path
50345050
t = self.fast_container_type(e, fullname)
50355051
if t:
50365052
return t
50375053

5054+
# if a ListExpr, just infer the item type directly
5055+
if isinstance(e, ListExpr):
5056+
item_types = [self.accept(item) for item in e.items]
5057+
if not item_types:
5058+
# empty list, default to Any
5059+
item_type = AnyType(TypeOfAny.from_empty_collection)
5060+
else:
5061+
# attempt to find a common supertype
5062+
item_type = self.infer_item_type(item_types)
5063+
return self.chk.named_generic_type(fullname, [item_type])
5064+
50385065
# Translate into type checking a generic function call.
50395066
# Used for list and set expressions, as well as for tuples
50405067
# containing star expressions that don't refer to a

0 commit comments

Comments
 (0)