Prefer if over match simple sequences and mappings
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
*argsor **kwargs - Has guards (
if...)
Can i take this?
@sobolevn im waiting for your response
Hi, @antriantsek! Thanks for your interest in this project. However, there are several things I want to highlight:
- 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.
- Pinging maintainers on unrelated issues is not very polite, please don't do that :)
im sorry about that... im in the middle of a school project thats why i disturb you :)
No worries, I will happy to help, but not right now :) In the meantime you can try to fix the CI yourself ❤️