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
9 changes: 5 additions & 4 deletions pycodestyle.py
Original file line number Diff line number Diff line change
Expand Up @@ -1067,7 +1067,8 @@ def is_string_literal(line):
line = line[1:]
return line and (line[0] == '"' or line[0] == "'")

allowed_try_keywords = ('try', 'except', 'else', 'finally')
allowed_keywords = (
'try', 'except', 'else', 'finally', 'with', 'if', 'elif')

if indent_level: # Allow imports in conditional statement/function
return
Expand All @@ -1081,9 +1082,9 @@ def is_string_literal(line):
yield 0, "E402 module level import not at top of file"
elif re.match(DUNDER_REGEX, line):
return
elif any(line.startswith(kw) for kw in allowed_try_keywords):
# Allow try, except, else, finally keywords intermixed with
# imports in order to support conditional importing
elif any(line.startswith(kw) for kw in allowed_keywords):
# Allow certain keywords intermixed with imports in order to
# support conditional or filtered importing
return
elif is_string_literal(line):
# The first literal is a docstring, allow it. Otherwise, report
Expand Down
15 changes: 15 additions & 0 deletions testsuite/E40.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,21 @@
finally:
print('made attempt to import foo')

import bar
#: Okay
with warnings.catch_warnings():
warnings.filterwarnings("ignore", DeprecationWarning)
import foo

import bar
Comment thread
EricCousineau-TRI marked this conversation as resolved.
#: Okay
if False:
import foo
elif not True:
import bar
else:
import mwahaha

import bar
#: E402
VERSION = '1.2.3'
Expand Down