Skip to content

Commit

Permalink
Micro-optimize flatten_nested_unions (#14368)
Browse files Browse the repository at this point in the history
Avoid constructing a new list if there is nothing to flatten (and the
input is a list, which is often the case).
  • Loading branch information
JukkaL authored Dec 29, 2022
1 parent 47747f2 commit 8884f7d
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 8884f7d

Please sign in to comment.