Skip to content

Speed up match checking after enum equality narrowing - #22003

Open
00200200 wants to merge 2 commits into
python:masterfrom
00200200:fix-21997-enum-match-union-narrow
Open

00200200 wants to merge 2 commits into
python:masterfrom
00200200:fix-21997-enum-match-union-narrow

Conversation

@00200200

@00200200 00200200 commented Sep 17, 2026

Copy link
Copy Markdown

Fixes #21997

After if x == SomeEnum.MEMBER: return, mypy stores the rest of the enum as a literal union. A later match x then did pairwise is_overlapping_types on those unions — O(N*M). On a 1200-member StrEnum that dominated cProfile.

I hash the simple items (Literal / None / Never) and keep the overlap check only for the rest (needed for things like float | complex narrowed by int).

Tested with the new MeetSuite case plus check-python310.test / check-enum.test / check-narrowing.test.

Equality checks explode enums into unions of literals. Intersecting
those unions used pairwise overlap tests, which is quadratic and made
match statements after an == check very slow. Hash simple items instead
and keep the overlap predicate only for the remaining cases.

Fixes python#21997.
Narrowed singleton items are ProperType after get_proper_type, so annotate
the list as list[Type] and read LiteralType.value from the proper item.
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Checking a match on an enum becomes quadratically slow after the variable was narrowed by an == check

1 participant