python / python/mypy

`match-case` does not work correctly with Literals vs Enums

Open
#20,142 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-enum topic-literal-types topic-match-statement
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

from enum import StrEnum
from typing import Literal, assert_never, reveal_type

class Color(StrEnum):
    RED = "r"
    GREEN = "g"
    BLUE = "b"

def test_literal_as_enum(x: Literal["g"] = "g") -> None:
    match x:
        case Color.RED:
            assert_never(x)
        case Color.GREEN:
            reveal_type(x)
        case Color.BLUE:
            assert_never(x)
        case _:
            assert_never(x)

def test_enum_as_litearl(y: Literal[Color.BLUE] = Color.BLUE) -> None:
    match y:
        case "r":
            assert_never(y)
        case "g":
            assert_never(y)
        case "b":
            reveal_type(y)
        case _:
            assert_never(y)

test_literal_as_enum()  # selects green branch at runtim
test_enum_as_litearl()  # selects blue branch at runtime

Expected no errors, but mypy-playground reports

main.py:14: error: Statement is unreachable  [unreachable]
main.py:18: error: Argument 1 to "assert_never" has incompatible type "Literal['g']"; expected "Never"  [arg-type]
main.py:27: error: Statement is unreachable  [unreachable]
main.py:29: error: Argument 1 to "assert_never" has incompatible type "Literal[Color.BLUE]"; expected "Never"  [arg-type]

Related: https://discuss.python.org/t/amend-pep-586-to-make-enum-values-subtypes-of-literal/59456
Also: #16327, #17162, #19616 (but none of these is specifically about match-case)

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 by reproducing the reported errors in the linked mypy-playground example with Python 3.12, master, and warn-unreachable enabled. Trace the match-case narrowing for Literal strings and StrEnum members, then use the shown assert_never and reveal_type checks as the completion criteria: the example should produce no errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.