Skip to content

Python · maintainability

prefer-match-type-dispatch

python:prefer-match-type-dispatch

Use `match` for explicit runtime type dispatch instead of branching parser machinery.

Code
SARJ080
Default
error
Fix
none
Languages
python

Why

Pattern matching makes type cases and sentinel cases explicit without control-flow exceptions or repeated dispatch checks.

Fix

Replace the detected guard or exception-driven dispatch with `match` arms for each supported value shape.

Before / after

Executed by this rule’s unit tests.

Before

Parser dispatches through sequential guards

app/parser.py · focus
def parse(value: object):
    if value is None:
        return value
    if isinstance(value, Unset):
        return value
    if isinstance(value, int):
        return str(value)
    return None

After

Parser names value shapes with match arms

app/parser.py · focus
def parse(value: object):
    match value:
        case None | Unset():
            return value
        case int():
            return str(value)
        case _:
            return None

Limits

  • The rule targets several measured shapes, including control-flow raises, sequential guards, and repeated `isinstance` dispatch.
  • Generated files and code that shadows `isinstance` are excluded; test files omit the control-flow-raise check.