Skip to content

Commit

Permalink
Speed up make_simplified_union (#14370)
Browse files Browse the repository at this point in the history
If there is only one non-union item, there's nothing interesting to do.
This is pretty common, and it avoids a fairly expensive
`_remove_redundant_union_items` call.

(Various small optimizations, including this, together netted a 6%
performance improvement in self check.)
  • Loading branch information
JukkaL committed Dec 29, 2022
1 parent 52172a3 commit 9183b28
Showing 1 changed file with 8 additions and 3 deletions.
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

0 comments on commit 9183b28

Please sign in to comment.