Skip to content

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 Group terminal format dispatch under one subject
app/formats.py
def parse_config(suffix: str, source: str, jsonc_is_valid: bool):
if suffix in {".yaml", ".yml"}:
return ("yaml", source)
if suffix == ".toml":
return ("toml", source)
if suffix == ".jsonc" and jsonc_is_valid:
return ("jsonc", source)
return None
After — preferred Retain grouped alternatives, the guard, and the fallback
app/formats.py
def parse_config(suffix: str, source: str, jsonc_is_valid: bool):
match suffix:
case ".yaml" | ".yml":
return ("yaml", source)
case ".toml":
return ("toml", source)
case ".jsonc" if jsonc_is_valid:
return ("jsonc", source)
case _:
return None
Before — flagged Make repeated filename dispatch explicit
app/migrate.py
_ESLINT_SUPPRESSIONS = "eslint.json"
_RATCHET_SUPPRESSIONS = "ratchet.json"
def migrate(path):
if path.name == _ESLINT_SUPPRESSIONS:
migrated = rewrite_eslint(path)
elif path.name == _RATCHET_SUPPRESSIONS:
migrated = rewrite_ratchet(path)
else:
migrated = rewrite(path)
return migrated
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)