Skip to content
Sarj Code Standards

prefer-match-value-dispatch

Prefer match/case for repeated dispatch on one value with a fallback.

Why

A single dispatch subject makes distinct value cases and their fallback easier to review.

Fix

Consider match/case while preserving fallback and constant semantics; use literal or dotted value patterns, never bare constant names that capture instead of compare. Review membership versus equality, subject evaluation, and guard order before rewriting.

Examples

Before — flagged Dispatch a stable parameter through literal cases
app/parse.py
def parse(kind):
if kind == "json":
return json_parser()
elif kind == "yaml":
return yaml_parser()
else:
return fallback()
pyproject.toml
[project]
requires-python = ">=3.10"
After — preferred Use value cases and retain the fallback
app/migrate.py
def migrate(path):
match path.name:
case "eslint.json":
return rewrite_eslint(path)
case "ratchet.json":
return rewrite_ratchet(path)
case _:
return rewrite(path)
Before — flagged Keep error variants and their fallback under one dispatch subject
app/errors.py
from provider import ErrorId
def classify(error_id):
if error_id == ErrorId.INSUFFICIENT:
return insufficient()
if error_id == ErrorId.INVALID_OPTION:
return invalid_option()
return rejected()
pyproject.toml
[project]
requires-python = ">=3.10"
After — preferred Value cases preserve the terminal fallback
app/errors.py
from provider import ErrorId
def classify(error_id):
match error_id:
case ErrorId.INSUFFICIENT:
return insufficient()
case ErrorId.INVALID_OPTION:
return invalid_option()
case _:
return rejected()