Python · style
prefer-walrus-regex-match
python:prefer-walrus-regex-match Bind a regex result in the `if` condition that immediately tests it.
- Code
- SARJ081
- Default
- error
- Fix
- none
- Languages
- python
Why
A named expression keeps the match operation and its condition together while preserving access to the result.
Fix
Move the regex call into the following condition as `if (match := pattern.search(text)):`.
Before / after
Executed by this rule’s unit tests.
Before
Regex result is assigned before its condition
import re
def first_number(text: str) -> str | None:
match = re.search(r"\d+", text)
if match:
return match.group(0)
return None
After
Regex result is bound in its condition
import re
def first_number(text: str) -> str | None:
if match := re.search(r"\d+", text):
return match.group(0)
return None
Limits
- Only a simple assignment immediately followed by a truthy or `is not None` check is analyzed.
- The assignment is retained when the result is used after the conditional or the regex receiver cannot be resolved.