From d887e9c0d090694b66b5fa20ac249b3d749a8518 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sun, 23 Apr 2023 07:19:16 -0600 Subject: [PATCH] Fix performance in union subtyping (#15104) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is a performance optimisation for subtyping between two unions that are largely the same. Fixes #14034 This makes @adriangb's example in https://github.com/python/mypy/issues/14034#issuecomment-1470252641 finish basically instantly. I could add it as a unit test? Type checking pydantic core is still not fast — takes like four or five minutes with uncompiled mypy — but at least it's now feasible. I think there's room for doing some optimisation in make_simplified_union that would improve this. --- mypy/subtypes.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 29ad86e5d99f..59919456ab5c 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -917,13 +917,9 @@ def visit_union_type(self, left: UnionType) -> bool: for item in _flattened(self.right.relevant_items()): p_item = get_proper_type(item) - if isinstance(p_item, LiteralType): - fast_check.add(p_item) - elif isinstance(p_item, Instance): - if p_item.last_known_value is None: - fast_check.add(p_item) - else: - fast_check.add(p_item.last_known_value) + fast_check.add(p_item) + if isinstance(p_item, Instance) and p_item.last_known_value is not None: + fast_check.add(p_item.last_known_value) for item in left.relevant_items(): p_item = get_proper_type(item)