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

Prefer if over match simple sequences and mappings

Open ZhdanovAM72 opened this issue 4 months ago • 5 comments

Rule request

Thesis

We should support simplifying match statements that use simple sequence and mapping patterns:

Example:

match data:
    case [1, 2]:
        handle_pair()
    case _:
        ignore()

Can be rewritten as:

if data == [1, 2]:
    handle_pair()
else:
    ignore()

Reasoning

Using match for exact structural comparisons of simple literals is unnecessarily verbose. While match excels at deconstruction, using it to check for an exact list or dict value is better expressed with a direct equality comparison (==), which is more readable and performant.

These patterns are common in configuration checks, API responses, and state validation.

When should this be allowed?

Only when:

  • There are exactly two cases (with case _:)
  • The first pattern is a simple sequence like [1, "a"] or a simple mapping like {"x": 1}
  • All elements/keys/values are simple (literals, constants, names)
  • No starred patterns (*rest) or variable bindings (case [x, y]:)
  • Keys in mappings are constants (not variables)

Not allowed if:

  • Uses deconstruction (e.g. case [x, y]:)
  • Contains *args or **kwargs
  • Has guards (if ...)

ZhdanovAM72 avatar Sep 13 '25 04:09 ZhdanovAM72

Can i take this?

ZhdanovAM72 avatar Sep 14 '25 05:09 ZhdanovAM72

@sobolevn im waiting for your response

antriantsek avatar Sep 14 '25 09:09 antriantsek

Hi, @antriantsek! Thanks for your interest in this project. However, there are several things I want to highlight:

  1. Your PR https://github.com/wemake-services/wemake-python-styleguide/pull/3524 does not work, it is very far from the solution. If you try to run this code - it probably even won't. If you are using AI for that - please, don't :) Since there are quite a lot of things to fix in this PR, I didn't have time yet to fully review it and guide you.
  2. Pinging maintainers on unrelated issues is not very polite, please don't do that :)

sobolevn avatar Sep 14 '25 11:09 sobolevn

im sorry about that... im in the middle of a school project thats why i disturb you :)

antriantsek avatar Sep 14 '25 11:09 antriantsek

No worries, I will happy to help, but not right now :) In the meantime you can try to fix the CI yourself ❤️

sobolevn avatar Sep 14 '25 11:09 sobolevn