Skip to content

Commit

Permalink
typeops: extend make_simplified_union fast path to enums
Browse files Browse the repository at this point in the history
In PR python#9192 a fast path was created to address the slowness reported
in issue python#9169 wherein large Union or literal types would dramatically
slow down typechecking.

It is desirable to extend this fast path to cover Enum types, as these
can also leverage the O(n) set-based fast path instead of the O(n**2)
fallback.

This is seen to bring down the typechecking of a single fairly simple
chain of `if` statements operating on a large enum (~3k members) from
~40min to 12s in real-world code! Note that the timing is taken from
a pure-python run of mypy, as opposed to a compiled version.
  • Loading branch information
hugues-aff committed Sep 2, 2020
1 parent 13ae58f commit 15b635e
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
since these may assume that MROs are ready.
"""

from typing import cast, Optional, List, Sequence, Set, Iterable, TypeVar
from typing import cast, Optional, List, Sequence, Set, Iterable, TypeVar, Tuple
from typing_extensions import Type as TypingType
import sys

Expand Down Expand Up @@ -346,16 +346,17 @@ def make_simplified_union(items: Sequence[Type],
removed = set() # type: Set[int]

# Avoid slow nested for loop for Union of Literal of strings (issue #9169)
if all((isinstance(item, LiteralType) and
item.fallback.type.fullname == 'builtins.str')
for item in items):
seen = set() # type: Set[str]
if all((isinstance(item, LiteralType) and (
item.fallback.type.is_enum or item.fallback.type.fullname == 'builtins.str'
)) for item in items):
seen = set() # type: Set[Tuple[str, str]]
for index, item in enumerate(items):
assert isinstance(item, LiteralType)
assert isinstance(item.value, str)
if item.value in seen:
k = (item.value, item.fallback.type.fullname)
if k in seen:
removed.add(index)
seen.add(item.value)
seen.add(k)

else:
for i, ti in enumerate(items):
Expand Down

0 comments on commit 15b635e

Please sign in to comment.