Skip to content

Instantly share code, notes, and snippets.

@utgwkk
Last active November 8, 2019 03:10
Show Gist options
  • Save utgwkk/7fea1bff082e0a9f069b870451a6e1bd to your computer and use it in GitHub Desktop.
Save utgwkk/7fea1bff082e0a9f069b870451a6e1bd to your computer and use it in GitHub Desktop.
boolをそのまま返せばいいのを検出するやつ
import sys
import ast
class TrueFalseDetected(Exception):
def __init__(self, lineno, col):
self.lineno = lineno
self.col = col
def __str__(self):
return 'Useless `if` detected at line {}, column {}'.format(self.lineno, self.col)
class CondTrueFalseDetector(ast.NodeVisitor):
def visit_IfExp(self, node):
if isinstance(node.body, ast.NameConstant) and isinstance(node.body.value, bool) and isinstance(node.orelse, ast.NameConstant) and isinstance(node.orelse.value, bool):
raise TrueFalseDetected(node.lineno, node.col_offset)
self.visit(node.test)
self.visit(node.body)
self.visit(node.orelse)
def visit_If(self, node):
if isinstance(node.body[0], ast.Return) and isinstance(node.body[0].value, ast.NameConstant) and isinstance(node.body[0].value.value, bool) and isinstance(node.orelse[0], ast.Return) and isinstance(node.orelse[0].value, ast.NameConstant) and isinstance(node.orelse[0].value.value, bool):
raise TrueFalseDetected(node.lineno, node.col_offset)
self.visit(node.test)
for n in node.body:
self.visit(n)
for n in node.orelse:
self.visit(n)
filename = sys.argv[1]
with open(filename) as f:
source = f.read()
tree = ast.parse(source, filename)
CondTrueFalseDetector().visit(tree)
print('OK')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment