@@ -572,6 +572,8 @@ def make_simplified_union(
572572 * [int, Any] -> Union[int, Any] (Any types are not simplified away!)
573573 * [Any, Any] -> Any
574574 * [int, Union[bytes, str]] -> Union[int, bytes, str]
575+ * [Literal[1]?, Literal[1]] -> Literal[1]?
576+ * Literal["max"]?, Literal["max", "sum"] -> Literal["max"]? | Literal["sum"]
575577
576578 Note: This must NOT be used during semantic analysis, since TypeInfos may not
577579 be fully initialized.
@@ -600,13 +602,32 @@ def make_simplified_union(
600602 ):
601603 simplified_set = try_contracting_literals_in_union (simplified_set )
602604
603- result = get_proper_type (UnionType .make_union (simplified_set , line , column ))
605+ # Step 5: Combine Literals and Instances with LKVs, e.g. Literal[1]?, Literal[1] -> Literal[1]?
606+ new_items = []
607+ for item in simplified_set :
608+ if isinstance (item , LiteralType ):
609+ # scan if there is an Instance with a last_known_value that matches
610+ for other in simplified_set :
611+ if (
612+ isinstance (other , Instance )
613+ and other .last_known_value is not None
614+ and item == other .last_known_value
615+ ):
616+ # do not include item
617+ break
618+ else :
619+ new_items .append (item )
620+ else :
621+ # If the item is not a LiteralType, we can use it directly.
622+ new_items .append (item )
623+
624+ result = get_proper_type (UnionType .make_union (new_items , line , column ))
604625
605626 nitems = len (items )
606627 if nitems > 1 and (
607628 nitems > 2 or not (type (items [0 ]) is NoneType or type (items [1 ]) is NoneType )
608629 ):
609- # Step 5 : At last, we erase any (inconsistent) extra attributes on instances.
630+ # Step 6 : At last, we erase any (inconsistent) extra attributes on instances.
610631
611632 # Initialize with None instead of an empty set as a micro-optimization. The set
612633 # is needed very rarely, so we try to avoid constructing it.
0 commit comments