Skip to content

Pattern matching is not exhaustive in a weird edge case with an enum member subject #18875

Closed as duplicate

Description

@injust

Bug Report

  1. Access an enum member by name, but the name cannot be inline (e.g. you can access it from a variable)
  2. Directly use the enum member as the subject in a match statement

If you do this, mypy does not think the match statement is exhaustive.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.13&flags=strict&gist=0d11136907ace743b0f2412ad0f26bb1

from enum import Enum, auto
from typing import reveal_type


class Thing(Enum):
    ONE = auto()
    TWO = auto()


two = "TWO"


def good() -> int:
    version = Thing[two]
    match version:
        case Thing.ONE:
            return 1
        case Thing.TWO:
            return 2


def bad() -> int:
    match Thing[two]:
        case Thing.ONE:
            return 1
        case Thing.TWO:
            return 2
        case _ as thing:
            reveal_type(thing)

If you replace Thing[two] with Thing["TWO"], the problem also goes away.

Expected Behavior

Both match statements are exhaustive, so there is a return statement for all cases.

Actual Behavior

main.py:22: error: Missing return statement  [return]
main.py:29: note: Revealed type is "__main__.Thing"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: --strict
  • Python version used: 3.13

Activity

  1. changed the title [-]Pattern matching is not exhaustive if enum member subject is accessed by name and the name is in a variable[/-] [+]Pattern matching is not exhaustive in a weird edge case with an enum member subject[/+] on Apr 3, 2025
  2. sterliakov commented on Apr 4, 2025

    @sterliakov
    Collaborator

    Given that your good version works, is it the same as #18440? Currently we do not narrow types of complex expressions in match statement other than function calls.

  3. injust commented on Apr 4, 2025

    @injust
    Author

    Given that your good version works, is it the same as #18440? Currently we do not narrow types of complex expressions in match statement other than function calls.

    Yes, it seems like the same issue. In the repro for #18440, if you change the function b from

    match d[k]:

    to

    foo = d[k]
    match foo:

    Then it type checks. This is the same behaviour that I'm seeing here.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions