From a66cf09c8d03322c38aea79eaccda9d03353414e Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 22 Dec 2022 16:10:15 +0000 Subject: [PATCH] Speed up make_simplified_union 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. --- mypy/typeops.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/mypy/typeops.py b/mypy/typeops.py index baf5b8552eff8..8c01fb1180765 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -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. @@ -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 @@ -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.