Skip to content

Commit

Permalink
Add visit_IfExp and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Agathiyan Bragadeesh committed May 21, 2020
1 parent dcdc3f6 commit 5cc25fe
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Unreleased

* Detect unreachable code in conditional expressions (#178)
* Report error codes in output, e.g., `code.py:1: V104 unused import ...`
(RJ722, #195).
* Support `# noqa` comments to suppress results from that line
Expand Down
17 changes: 17 additions & 0 deletions tests/test_conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,20 @@ def test_redundant_if(v):
)
print(v.unreachable_code[0].size)
check_unreachable(v, 1, 2, "if")


def test_if_exp_true(v):
v.scan(
"""\
foo if True else bar
"""
)
check_unreachable(v, 1, 1, "ternary")

def test_if_exp_false(v):
v.scan(
"""\
foo if False else bar
"""
)
check_unreachable(v, 1, 1, "ternary")
16 changes: 14 additions & 2 deletions vulture/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,17 +402,26 @@ def _add_aliases(self, node):

def _handle_conditional_node(self, node, name):
if utils.condition_is_always_false(node.test):
last_node = node.body if isinstance(node, ast.IfExp) else node.body[-1]
self._define(
self.unreachable_code,
name,
node,
last_node=node.body[-1],
last_node=last_node,
message="unsatisfiable '{name}' condition".format(**locals()),
confidence=100,
)
elif utils.condition_is_always_true(node.test):
else_body = node.orelse
if else_body:
if name == "ternary":
self._define(
self.unreachable_code,
name,
else_body,
message="unreachable 'else' expression",
confidence=100,
)
elif else_body:
self._define(
self.unreachable_code,
"else",
Expand Down Expand Up @@ -575,6 +584,9 @@ def visit_FunctionDef(self, node):
def visit_If(self, node):
self._handle_conditional_node(node, "if")

def visit_IfExp(self, node):
self._handle_conditional_node(node, "ternary")

def visit_Import(self, node):
self._add_aliases(node)

Expand Down

0 comments on commit 5cc25fe

Please sign in to comment.