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