@@ -571,6 +571,8 @@ def make_simplified_union(
571
571
* [int, Any] -> Union[int, Any] (Any types are not simplified away!)
572
572
* [Any, Any] -> Any
573
573
* [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"]
574
576
575
577
Note: This must NOT be used during semantic analysis, since TypeInfos may not
576
578
be fully initialized.
@@ -599,13 +601,32 @@ def make_simplified_union(
599
601
):
600
602
simplified_set = try_contracting_literals_in_union (simplified_set )
601
603
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 ))
603
624
604
625
nitems = len (items )
605
626
if nitems > 1 and (
606
627
nitems > 2 or not (type (items [0 ]) is NoneType or type (items [1 ]) is NoneType )
607
628
):
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.
609
630
610
631
# Initialize with None instead of an empty set as a micro-optimization. The set
611
632
# is needed very rarely, so we try to avoid constructing it.
0 commit comments