python / python/mypy

mypy reports false-positive [exhaustive-match] error when there is an unreachable match

Open
#21,517 1 comment 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

exhaustive-match incorrectly reports a missing A case when using a capture pattern (case A() as a) together with an unreachable extra branch.

The following code reports:

error: Match statement has unhandled case for values of type "A"  [exhaustive-match]

even though all possible values of A | None are handled.

Interestingly, the error disappears if the unreachable case B(): branch is removed.

This seems related to exhaustiveness analysis for class patterns with as captures.

To Reproduce

# mypy: enable-error-code=exhaustive-match

class A: pass
class B: pass

x: A | None

match x:
    case None:
        pass
    case A() as a:
        pass
    case B():
        pass

Expected Behavior

No errors should be reported.

x has type A | None, and both None and A are handled exhaustively.

The case B(): branch is unreachable and should not affect exhaustiveness checking.

Removing the case B(): branch currently makes mypy report no errors:

match x:
    case None:
        pass
    case A() as a:
        pass

Actual Behavior

main.py:8: error: Match statement has unhandled case for values of type "A"  [exhaustive-match]
main.py:8: note: If match statement is intended to be non-exhaustive, add `case _: pass`
Found 1 error in 1 file (checked 1 source file)

Your Environment

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 main.py reproduction and the exhaustive-match analysis for class patterns with as captures. Verify that the A | None cases produce no error and that the unreachable case B(): branch does not change exhaustiveness checking.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
65/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.