From 8884f7d38c4ee190068666b633e4433d27c8293e Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 29 Dec 2022 13:42:22 +0000 Subject: [PATCH] Micro-optimize flatten_nested_unions (#14368) Avoid constructing a new list if there is nothing to flatten (and the input is a list, which is often the case). --- mypy/types.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/mypy/types.py b/mypy/types.py index e25630e794db..fa1502f48fa4 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -3381,12 +3381,20 @@ def _flattened(types: Iterable[Type]) -> Iterable[Type]: def flatten_nested_unions( - types: Iterable[Type], handle_type_alias_type: bool = True + types: Sequence[Type], handle_type_alias_type: bool = True ) -> list[Type]: """Flatten nested unions in a type list.""" + if not isinstance(types, list): + typelist = list(types) + else: + typelist = cast("list[Type]", types) + + # Fast path: most of the time there is nothing to flatten + if not any(isinstance(t, (TypeAliasType, UnionType)) for t in typelist): # type: ignore[misc] + return typelist + flat_items: list[Type] = [] - # TODO: avoid duplicate types in unions (e.g. using hash) - for t in types: + for t in typelist: tp = get_proper_type(t) if handle_type_alias_type else t if isinstance(tp, ProperType) and isinstance(tp, UnionType): flat_items.extend(