Skip to content

Commit

Permalink
'FalsyConstantCompareViolation' counts 'NamedExpr' #1201 (#1253)
Browse files Browse the repository at this point in the history
  • Loading branch information
edytagarbarz authored Mar 12, 2020
1 parent 7d98e40 commit e45bbb1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest

from wemake_python_styleguide.compat.constants import PY38
from wemake_python_styleguide.violations.refactoring import (
FalsyConstantCompareViolation,
WrongIsCompareViolation,
Expand All @@ -8,13 +9,26 @@
WrongConstantCompareVisitor,
)

wrong_comparators = (
wrong_comparators = [
('some', '[]'),
('some', '{}'), # noqa: P103
('some', '()'),
('[]', 'some'),
('{}', 'some'), # noqa: P103
('()', 'some'),
]

if PY38:
wrong_comparators.extend([
('some', '(x := [])'),
('(x := [])', 'some'),
])

correct_walrus = pytest.param(
['(x := [1, 2])', 'some'],
marks=pytest.mark.skipif(
not PY38, reason='walrus appeared in 3.8',
),
)


Expand Down Expand Up @@ -92,8 +106,8 @@ def test_falsy_constant_not_eq(
('some', 'other.attr'),
('some', 'other.method()'),
('some', 'other[0]'),
('None', 'some'),
correct_walrus,
])
def test_correct_constant_compare(
assert_errors,
Expand Down
10 changes: 5 additions & 5 deletions wemake_python_styleguide/visitors/ast/compares.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,13 @@ def visit_Compare(self, node: ast.Compare) -> None:
def _check_constant(self, op: ast.cmpop, comparator: ast.expr) -> None:
if not isinstance(op, (ast.Eq, ast.NotEq, ast.Is, ast.IsNot)):
return

if not isinstance(comparator, (ast.List, ast.Dict, ast.Tuple)):
real = get_assigned_expr(comparator)
if not isinstance(real, (ast.List, ast.Dict, ast.Tuple)):
return

length = len(comparator.keys) if isinstance(
comparator, ast.Dict,
) else len(comparator.elts)
length = len(real.keys) if isinstance(
real, ast.Dict,
) else len(real.elts)

if not length:
self.add_violation(FalsyConstantCompareViolation(comparator))
Expand Down

0 comments on commit e45bbb1

Please sign in to comment.