Skip to content
Merged
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 @@ -21,6 +21,7 @@ Semantic versioning in our case means:
### Bugfixes

- Fixes the false positive `WPS222` for nested conditions, #3630
- Fixes the false positive `WPS529` for dict subscripts in the `else` branch, #3501


## 1.6.1
Expand Down
28 changes: 28 additions & 0 deletions tests/test_visitors/test_ast/test_subscripts/test_implicit_get.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@
...
"""

else_subscripts = """
if 'a' in kwargs:
pass
else:
kwargs['a'] = other(kwargs)
"""


@pytest.mark.parametrize(
'template',
Expand Down Expand Up @@ -122,3 +129,24 @@ def test_correct_if(
visitor.run()

assert_errors(visitor, [])


@pytest.mark.parametrize(
'code',
[
else_subscripts,
],
)
def test_no_implicit_dict_get_in_else_branch(
assert_errors,
parse_ast_tree,
default_options,
code,
):
"""Testing that subscripts in `else` branch do not trigger violation."""
tree = parse_ast_tree(code)

visitor = ImplicitDictGetVisitor(default_options, tree=tree)
visitor.run()

assert_errors(visitor, [])
1 change: 0 additions & 1 deletion wemake_python_styleguide/violations/refactoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -1135,7 +1135,6 @@ class ImplicitDictGetViolation(ASTViolation):
print(collection[key])

.. versionadded:: 0.13.0

"""

error_template = 'Found implicit `.get()` dict usage'
Expand Down
8 changes: 7 additions & 1 deletion wemake_python_styleguide/visitors/ast/subscripts.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ast
from collections.abc import Iterator
from typing import ClassVar, final

from wemake_python_styleguide.logic import source
Expand Down Expand Up @@ -127,6 +128,11 @@ def visit_If(self, node: ast.If) -> None:
self._check_implicit_get(node)
self.generic_visit(node)

def _walk_body(self, body: list[ast.stmt]) -> Iterator[ast.AST]:
Comment thread
sobolevn marked this conversation as resolved.
"""Yields all nodes strictly within a list of statements."""
for stmt in body:
yield from ast.walk(stmt)

def _check_implicit_get(self, node: ast.If) -> None:
if not isinstance(node.test, ast.Compare):
return
Expand All @@ -136,7 +142,7 @@ def _check_implicit_get(self, node: ast.If) -> None:
checked_key = source.node_to_string(node.test.left)
checked_collection = source.node_to_string(node.test.comparators[0])

for sub in ast.walk(node):
for sub in self._walk_body(node.body):
Comment thread
vldmrdev marked this conversation as resolved.
if not isinstance(sub, ast.Subscript):
continue

Expand Down