Skip to content

Python · correctness

prefer-match-assert-never

python:prefer-match-assert-never

Closed-set dispatch should fail explicitly when a variant is unhandled.

Code
SARJ032
Default
error
Fix
none
Languages
python

Why

A silent wildcard, `else`, or incomplete dispatch map lets newly added variants pass unnoticed.

Fix

Handle every variant and use `assert_never` or an explicit exception for the unreachable fallthrough.

Before / after

Executed by this rule’s unit tests.

Before

Closed-set match silently ignores a variant

dispatch.py · focus
from kinds import Kind

def handle(kind):
    match kind:
        case Kind.A:
            handle_a()
        case Kind.B:
            handle_b()
        case _:
            pass

After

Closed-set match rejects an unhandled variant

dispatch.py · focus
from kinds import Kind

def handle(kind):
    match kind:
        case Kind.A:
            handle_a()
        case Kind.B:
            handle_b()
        case _:
            raise AssertionError(kind)

Limits

  • The rule recognizes closed sets from local classes, enums, imported member owners, and static handler maps.
  • Guarded matches, dynamically grown maps, and open-ended value domains are excluded.