Skip to content

Commit

Permalink
Inspect for loops variables
Browse files Browse the repository at this point in the history
  • Loading branch information
gforcada committed Mar 17, 2018
1 parent d4fb6a3 commit 7580be7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
21 changes: 21 additions & 0 deletions flake8_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ def run(self):
elif isinstance(statement, ast.FunctionDef):
value = self.check_function_definition(statement)

elif isinstance(statement, ast.For):
value = self.check_for_loop(statement)

if value:
for line, offset, msg, rtype in value:
yield line, offset, msg, rtype
Expand Down Expand Up @@ -119,3 +122,21 @@ def check_function_definition(self, statement):
self.argument_msg.format(arg.id),
type(self),
)

def check_for_loop(self, statement):
if isinstance(statement.target, ast.Tuple):
for name in statement.target.elts:
if name.id in BUILTINS:
yield (
statement.lineno,
statement.col_offset,
self.argument_msg.format(name.id),
type(self),
)
elif statement.target.id in BUILTINS:
yield (
statement.lineno,
statement.col_offset,
self.argument_msg.format(statement.target.id),
type(self),
)
21 changes: 12 additions & 9 deletions run_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,19 @@ def test_ignore_whitelisted_names(self):
ret = [c for c in checker.run()]
self.assertEqual(len(ret), 0)

def test_regression_14(self):
def test_for_loop_variable(self):
tree = ast.parse(
'from datetime import datetime\n'
'def validate_date(date):\n'
" valid_formats = ['%d.%m.%y', '%d.%m.%Y']\n"
' for format in valid_formats:\n'
' try:\n'
' return datetime.strptime(date, format)\n'
' except ValueError:\n'
' continue\n'
'for format in (1, 2, 3):\n'
' continue\n',
)
checker = BuiltinsChecker(tree, '/home/script.py')
ret = [c for c in checker.run()]
self.assertEqual(len(ret), 1)

def test_for_loop_multiple_variables(self):
tree = ast.parse(
'for (index, format) in enumerate([1,2,3,]):\n'
' continue\n',
)
checker = BuiltinsChecker(tree, '/home/script.py')
ret = [c for c in checker.run()]
Expand Down

0 comments on commit 7580be7

Please sign in to comment.