Skip to content
Sarj Code Standards

prefer-match-none-check

Handle present values before an unconditional None arm in optional-value matches.

Why

A presence check expresses a binary choice directly. For structural dispatch, leading with the concrete cases shows what each value does, and a later None arm handles absence.

Fix

Move the unconditional case None: below the concrete value cases while keeping a final catchall last. When absence exits early or the present arm is pass, use a guard clause such as if (value := lookup()) is None: raise ...; when absence is pass, use if (value := lookup()) is not None:. Otherwise prefer if value is not None: with an else for absence.

Examples

Before — flagged An unconditional None case precedes a concrete variant
service.py
def render(value):
match value:
case None:
return "missing"
case str() as text:
return text.upper()
case _:
return "other"
After — preferred Concrete variants precede None and the fallback stays last
service.py
def render(value):
match value:
case str() as text:
return text.upper()
case None:
return "missing"
case _:
return "other"
Before — flagged A binary None match can use an explicit identity check
service.py
def render(value):
match value:
case None:
return "missing"
case _:
return str(value)
After — preferred An explicit identity check handles present and absent values
service.py
def render(value):
if value is not None:
return str(value)
return "missing"
Before — flagged A lookup returned under `is not None` is bound in its guard
service.py
def label(labels, key):
found = labels.get(key)
if found is not None:
return found.title()
return "unknown"
After — preferred A lookup is evaluated once in the guard that consumes it
service.py
def label(labels, key):
if (found := labels.get(key)) is not None:
return found.title()
return "unknown"
Autofix output
service.py
def label(labels, key):
if (found := labels.get(key)) is not None:
return found.title()
return "unknown"

Formerly: prefer-walrus-none-guard