Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Semantic versioning in our case means:
### Features

- Adds `WPS365`: match statement can be simplified to `if`, #3520
- Adds `WPS366`: match sequence or mapping can be simplified to `if`, #3527


## 1.4.0
Expand Down
11 changes: 11 additions & 0 deletions tests/fixtures/noqa/noqa.py
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,17 @@ def many_raises_function(parameter): # noqa: WPS238
case _:
...

match data: # noqa: WPS366
case [1, 2]:
...
case _:
...

match data: # noqa: WPS366
case {'x': 1, 'y': 2}:
...
case _:
...

my_print("""
text
Expand Down
1 change: 1 addition & 0 deletions tests/test_checker/test_noqa.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@
'WPS363': 1,
'WPS364': 1,
'WPS365': 1,
'WPS366': 2,
'WPS400': 0, # defined in ignored violations.
'WPS401': 0, # logically unacceptable.
'WPS402': 0, # defined in ignored violations.
Expand Down
3,532 changes: 3,524 additions & 8 deletions tests/test_formatter/__snapshots__/test_formatter_output.ambr

Large diffs are not rendered by default.

167 changes: 167 additions & 0 deletions tests/test_visitors/test_ast/test_conditions/test_match_conditions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import pytest

from wemake_python_styleguide.violations.consistency import (
SimplifiableSequenceOrMappingMatchViolation,
)
from wemake_python_styleguide.visitors.ast.conditions import (
SimplifiableSequenceOrMappingMatchVisitor,
)

# Wrong:
simple_sequence = """
match data:
case {0}:
pass
case _:
pass
"""

simple_mapping = """
match data:
case {0}:
pass
case _:
pass
"""


# Correct:
binding_sequence = """
match data:
case [x]:
pass
case _:
pass
"""

starred_sequence = """
match data:
case [1, *rest]:
pass
case _:
pass
"""

starred_mapping = """
match data:
case {'x': 1, **value}:
pass
case _:
pass
"""

mapping_with_binding = """
match data:
case {"x": value}:
pass
case _:
pass
"""

with_guard = """
match data:
case [1, 2] if flag:
pass
case _:
pass
"""

as_binding = """
match data:
case [1, 2] as x:
pass
case _:
pass
"""

complex_sequence = """
match data:
case [1, [3, 4]]:
pass
case _:
pass
"""

complex_name = """
match data:
case [some_var]:
pass
case _:
pass
"""

three_cases = """
match data:
case [1]:
pass
case [2]:
pass
case _:
pass
"""


@pytest.mark.parametrize(
'code',
[
[1, 'a'],
[2, 3],
['x', 'y'],
],
)
def test_simplifiable_sequence_match_violation(
code, assert_errors, parse_ast_tree, default_options
):
"""Test that simple sequence match raises a violation."""
tree = parse_ast_tree(simple_sequence.format(code))
visitor = SimplifiableSequenceOrMappingMatchVisitor(
default_options, tree=tree
)
visitor.run()
assert_errors(visitor, [SimplifiableSequenceOrMappingMatchViolation])


@pytest.mark.parametrize(
'code',
[
{'a': 1},
{'x': 2, 'y': 3},
{4: 'b'},
],
)
def test_simplifiable_mapping_match_violation(
code, assert_errors, parse_ast_tree, default_options
):
"""Test that simple mapping match raises a violation."""
tree = parse_ast_tree(simple_mapping.format(code))
visitor = SimplifiableSequenceOrMappingMatchVisitor(
default_options, tree=tree
)
visitor.run()
assert_errors(visitor, [SimplifiableSequenceOrMappingMatchViolation])


@pytest.mark.parametrize(
'code',
[
binding_sequence,
starred_sequence,
mapping_with_binding,
with_guard,
as_binding,
complex_sequence,
complex_name,
three_cases,
starred_mapping,
],
)
def test_not_simplifiable_structural_match(
code, assert_errors, parse_ast_tree, default_options
):
"""Test that complex or non-simplifiable matches do not raise violations."""
tree = parse_ast_tree(code)
visitor = SimplifiableSequenceOrMappingMatchVisitor(
default_options, tree=tree
)
visitor.run()
assert_errors(visitor, [])
57 changes: 0 additions & 57 deletions wemake_python_styleguide/logic/tree/pattern_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,60 +45,3 @@ def is_constant_subject(condition: ast.AST | list[ast.expr]) -> bool:
and is_constant_subject(node.values)
)
return False


def is_wildcard_pattern(case: ast.match_case) -> bool:
"""Returns True only for `case _:`."""
pattern = case.pattern
return (
isinstance(pattern, ast.MatchAs)
and pattern.pattern is None
and pattern.name is None
)


def is_simple_pattern(pattern: ast.pattern) -> bool:
"""Returns True if the pattern is simple enough to replace with `==`."""
return _is_simple_value_or_singleton(pattern) or _is_simple_composite(
pattern
)


def _is_simple_composite(pattern: ast.pattern) -> bool:
"""Returns True/False for MatchOr and MatchAs, None otherwise."""
if isinstance(pattern, ast.MatchOr):
return all(is_simple_pattern(sub) for sub in pattern.patterns)
if isinstance(pattern, ast.MatchAs):
inner = pattern.pattern
return inner is not None and is_simple_pattern(inner)
return False


def _is_simple_value_or_singleton(pattern: ast.pattern) -> bool:
"""
Checks if a pattern is a simple literal or singleton.

Supports:
- Single values: ``1``, ``"text"``, ``ns.CONST``.
- Singleton values: ``True``, ``False``, ``None``.
"""
if isinstance(pattern, ast.MatchSingleton):
return True
if isinstance(pattern, ast.MatchValue):
return isinstance(
pattern.value, (ast.Constant, ast.Name, ast.Attribute)
)
return False


def is_irrefutable_binding(pattern: ast.pattern) -> bool:
"""
Returns True for patterns like ``case x:`` or ``case data:``.

These always match and just bind the subject to a name.
"""
return (
isinstance(pattern, ast.MatchAs)
and pattern.pattern is None
and pattern.name is not None
)
94 changes: 94 additions & 0 deletions wemake_python_styleguide/logic/tree/simple_pattern_matching.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import ast


def is_wildcard_pattern(case: ast.match_case) -> bool:
"""Returns True only for `case _:`."""
pattern = case.pattern
return (
isinstance(pattern, ast.MatchAs)
and pattern.pattern is None
and pattern.name is None
)


def is_simple_pattern(pattern: ast.pattern) -> bool:
"""Returns True if the pattern is simple enough to replace with `==`."""
return _is_simple_value_or_singleton(pattern) or _is_simple_composite(
pattern
)


def _is_simple_composite(pattern: ast.pattern) -> bool:
"""Returns True/False for MatchOr and MatchAs, None otherwise."""
if isinstance(pattern, ast.MatchOr):
return all(is_simple_pattern(sub) for sub in pattern.patterns)
if isinstance(pattern, ast.MatchAs):
inner = pattern.pattern
return inner is not None and is_simple_pattern(inner)
return False


def _is_simple_value_or_singleton(pattern: ast.pattern) -> bool:
"""
Checks if a pattern is a simple literal or singleton.

Supports:
- Single values: ``1``, ``"text"``, ``ns.CONST``.
- Singleton values: ``True``, ``False``, ``None``.
"""
if isinstance(pattern, ast.MatchSingleton):
return True
if isinstance(pattern, ast.MatchValue):
return isinstance(
pattern.value, (ast.Constant, ast.Name, ast.Attribute)
)
return False


def is_irrefutable_binding(pattern: ast.pattern) -> bool:
"""
Returns True for patterns like ``case x:`` or ``case data:``.

These always match and just bind the subject to a name.
"""
return (
isinstance(pattern, ast.MatchAs)
and pattern.pattern is None
and pattern.name is not None
)


def has_binding_or_starred_patterns(pattern: ast.pattern) -> bool:
"""Returns True if the pattern binds any variables or uses *rest/**rest."""
if isinstance(pattern, ast.MatchAs):
return pattern.name is not None

if isinstance(pattern, ast.MatchSequence):
return any(
has_binding_or_starred_patterns(pattern)
for pattern in pattern.patterns
)

if isinstance(pattern, ast.MatchMapping):
return (
any(
has_binding_or_starred_patterns(pattern)
for pattern in pattern.patterns
)
or pattern.rest is not None
)

return bool(isinstance(pattern, ast.MatchStar))


def is_simple_sequence_or_mapping_pattern(pattern: ast.pattern) -> bool:
"""
Check that all elements in sequence/mapping are simple.

Simple is (literals, constants, names).
"""
if isinstance(pattern, ast.MatchSequence):
return all(is_simple_pattern(pattern) for pattern in pattern.patterns)
if isinstance(pattern, ast.MatchMapping):
return all(is_simple_pattern(pattern) for pattern in pattern.patterns)
return False
1 change: 1 addition & 0 deletions wemake_python_styleguide/presets/types/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
conditions.MatchVisitor,
conditions.ChainedIsVisitor,
conditions.SimplifiableMatchVisitor,
conditions.SimplifiableSequenceOrMappingMatchVisitor,
conditions.LeakingForLoopVisitor,
iterables.IterableUnpackingVisitor,
blocks.AfterBlockVariablesVisitor,
Expand Down
Loading
Loading