Prefer if over match with single-case
Rule request
Thesis
We should support simplifying match statements with only one case and no wildcard:
Example:
match x:
case 1:
do_something()
Can be rewritten as:
if x == 1:
do_something()
Reasoning
Even without an else branch, a single-case match is unnecessarily complex compared to a simple if. The intent is clear, and using if reduces nesting and cognitive load.
This is especially common in validation or dispatch logic where only one condition matters.
When should this be allowed?
Only when:
- There is exactly one case
- The pattern is simple (literal, constant, enum, etc.)
- No guard (
if...) is used
Originally posted by @sobolevn in https://github.com/wemake-services/wemake-python-styleguide/pull/3526#pullrequestreview-3218365781
Thank you for considering this proposal. I would like to work on implementing this new rule. I propose the error message like "Found simplifiable match statement: replace 'match' with 'if'". I will add a new configuration option --simplifiable-max-match-cases that will allow users to set the threshold. The default value will be 1.
No, we don't need any configuration here. Any match with just one case can be converted to if, see https://github.com/wemake-services/wemake-python-styleguide/commit/3246459d13023a7954b29654a8b2727f1bb57976
You can reuse its logic and violation. Only need new tests and new condition.