Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ def make_simplified_union(
* [int, int] -> int
* [int, Any] -> Union[int, Any] (Any types are not simplified away!)
* [Any, Any] -> Any
* [int, Union[bytes, str]] -> Union[int, bytes, str]

Note: This must NOT be used during semantic analysis, since TypeInfos may not
be fully initialized.
Expand All @@ -455,10 +456,14 @@ def make_simplified_union(
# Step 1: expand all nested unions
items = flatten_nested_unions(items)

# Step 2: remove redundant unions
# Step 2: fast path for single item
if len(items) == 1:
return get_proper_type(items[0])

# Step 3: remove redundant unions
simplified_set: Sequence[Type] = _remove_redundant_union_items(items, keep_erased)

# Step 3: If more than one literal exists in the union, try to simplify
# Step 4: If more than one literal exists in the union, try to simplify
if (
contract_literals
and sum(isinstance(get_proper_type(item), LiteralType) for item in simplified_set) > 1
Expand All @@ -471,7 +476,7 @@ def make_simplified_union(
if nitems > 1 and (
nitems > 2 or not (type(items[0]) is NoneType or type(items[1]) is NoneType)
):
# Step 4: At last, we erase any (inconsistent) extra attributes on instances.
# Step 5: At last, we erase any (inconsistent) extra attributes on instances.

# Initialize with None instead of an empty set as a micro-optimization. The set
# is needed very rarely, so we try to avoid constructing it.
Expand Down