python / python/mypy

Exhaustiveness checks (assert_never) don't work with 2-tuple of enums

Open
#16,722 7 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

The code below fails to type check, but should succeed because it's exhaustive.

There are some possibly related issues, but I don't know if they are all the same bug, the other tickets tend to depend on Union which this does not: #16650 #15426 #12364

To Reproduce

Playground link: https://mypy-play.net/?mypy=latest&python=3.12&gist=0d21d288fce8aa13d3cc60f4e418960a

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from enum import Enum
from typing import assert_never

class A(Enum):
    A0 = 0
    A1 = 1

class B(Enum):
    B0 = 0
    B1 = 1

def test(a: A, b: B) -> bool:
    match (a, b):
        case (A.A0, B.B0):
            return True
        case (A.A0, B.B1):
            return True
        case (A.A1, B.B0):
            return True
        case (A.A1, B.B1):
            return True
        case _ as never:
            assert_never(never)

    return False

Actual Behavior

typecheck_test.py:26: error: Argument 1 to "assert_never" has incompatible type "tuple[A, B]"; expected "NoReturn"  [arg-type]

Your Environment

  • Mypy version used: 1.8.0
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.11 (but also happens with 3.12 in playground link)

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 supplied two-enum tuple example in the linked mypy playground or a local mypy checkout, then inspect the exhaustiveness-checking path for structural pattern matching and assert_never. Done means the example type-checks without the incompatible tuple[A, B] error while preserving the existing behavior for non-exhaustive matches.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.