Skip to content

prefer-walrus-regex-match

A proven regex Match-or-None result is assigned only for the following condition.

Why

A named expression can keep a short regex operation with its only condition while preserving access to the result.

Fix

For a truthy check, use if (match := pattern.search(text)):. For an explicit None check, preserve it as if (match := pattern.search(text)) is not None:.

Examples

Before — flagged Regex result is assigned before its condition
app/parser.py
import re
def first_number(text: str) -> str | None:
match = re.search(r"\d+", text)
if match:
return match.group(0)
return None
After — preferred Regex result is bound in its condition
app/parser.py
import re
def first_number(text: str) -> str | None:
if match := re.search(r"\d+", text):
return match.group(0)
return None