python / python/mypy

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

Open
#21,997 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

performance topic-enum
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Type-checking a match on a large enum becomes very slow when the variable was first narrowed by an == check with an early exit:

from enum import StrEnum

class E(StrEnum):
    M0 = "m0"
    M1 = "m1"
    # ... 1,200 members

def f(x: E) -> None:
    if x == E.M0:
        return
    match x:
        case E.M1:
            pass
        # ... through case E.M7

Removing the x == E.M0 block makes this much faster (~1.5s vs 22s locally).

To Reproduce

Your Environment

  • Mypy version used: 2.3.1, 2.4.0+dev.4d195a2
  • Python version used: 3.12

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked Playground reproduction and compare the type-checking time with and without the early x == E.M0 check. Trace the enum narrowing and match-checking paths in mypy, then verify that the large-enum example no longer becomes quadratically slow while preserving the reported narrowing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.