wemake-python-styleguide icon indicating copy to clipboard operation
wemake-python-styleguide copied to clipboard

Prefer if over match with single-case

Open ZhdanovAM72 opened this issue 4 months ago • 2 comments

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:

  1. There is exactly one case
  2. The pattern is simple (literal, constant, enum, etc.)
  3. No guard (if ...) is used

Originally posted by @sobolevn in https://github.com/wemake-services/wemake-python-styleguide/pull/3526#pullrequestreview-3218365781

ZhdanovAM72 avatar Sep 13 '25 04:09 ZhdanovAM72

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.

alexeev-prog avatar Sep 13 '25 13:09 alexeev-prog

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.

sobolevn avatar Sep 13 '25 17:09 sobolevn