Skip to content

Commit 9183b28

Browse files
authored
Speed up make_simplified_union (#14370)
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.)
1 parent 52172a3 commit 9183b28

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

mypy/typeops.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,7 @@ def make_simplified_union(
441441
* [int, int] -> int
442442
* [int, Any] -> Union[int, Any] (Any types are not simplified away!)
443443
* [Any, Any] -> Any
444+
* [int, Union[bytes, str]] -> Union[int, bytes, str]
444445
445446
Note: This must NOT be used during semantic analysis, since TypeInfos may not
446447
be fully initialized.
@@ -455,10 +456,14 @@ def make_simplified_union(
455456
# Step 1: expand all nested unions
456457
items = flatten_nested_unions(items)
457458

458-
# Step 2: remove redundant unions
459+
# Step 2: fast path for single item
460+
if len(items) == 1:
461+
return get_proper_type(items[0])
462+
463+
# Step 3: remove redundant unions
459464
simplified_set: Sequence[Type] = _remove_redundant_union_items(items, keep_erased)
460465

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

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

0 commit comments

Comments
 (0)