@@ -580,6 +580,8 @@ def make_simplified_union(
580580 * [int, Any] -> Union[int, Any] (Any types are not simplified away!)
581581 * [Any, Any] -> Any
582582 * [int, Union[bytes, str]] -> Union[int, bytes, str]
583+ * [Literal[1]?, Literal[1]] -> Literal[1]?
584+ * Literal["max"]?, Literal["max", "sum"] -> Literal["max"]? | Literal["sum"]
583585
584586 Note: This must NOT be used during semantic analysis, since TypeInfos may not
585587 be fully initialized.
@@ -608,13 +610,32 @@ def make_simplified_union(
608610 ):
609611 simplified_set = try_contracting_literals_in_union (simplified_set )
610612
611- result = get_proper_type (UnionType .make_union (simplified_set , line , column ))
613+ # Step 5: Combine Literals and Instances with LKVs, e.g. Literal[1]?, Literal[1] -> Literal[1]?
614+ new_items = []
615+ for item in simplified_set :
616+ if isinstance (item , LiteralType ):
617+ # scan if there is an Instance with a last_known_value that matches
618+ for other in simplified_set :
619+ if (
620+ isinstance (other , Instance )
621+ and other .last_known_value is not None
622+ and item == other .last_known_value
623+ ):
624+ # do not include item
625+ break
626+ else :
627+ new_items .append (item )
628+ else :
629+ # If the item is not a LiteralType, we can use it directly.
630+ new_items .append (item )
631+
632+ result = get_proper_type (UnionType .make_union (new_items , line , column ))
612633
613634 nitems = len (items )
614635 if nitems > 1 and (
615636 nitems > 2 or not (type (items [0 ]) is NoneType or type (items [1 ]) is NoneType )
616637 ):
617- # Step 5 : At last, we erase any (inconsistent) extra attributes on instances.
638+ # Step 6 : At last, we erase any (inconsistent) extra attributes on instances.
618639
619640 # Initialize with None instead of an empty set as a micro-optimization. The set
620641 # is needed very rarely, so we try to avoid constructing it.
0 commit comments