Skip to content

Commit bc57ff0

Browse files
committed
Merge branch 'issue-304'
2 parents 40b1861 + d6da0b8 commit bc57ff0

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

pep8.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,6 @@
4747
"""
4848
from __future__ import with_statement
4949

50-
__version__ = '1.6.0a0'
51-
5250
import os
5351
import sys
5452
import re
@@ -64,6 +62,8 @@
6462
except ImportError:
6563
from ConfigParser import RawConfigParser
6664

65+
__version__ = '1.6.0a0'
66+
6767
DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git,__pycache__,.tox'
6868
DEFAULT_IGNORE = 'E123,E226,E24,E704'
6969
try:
@@ -850,7 +850,8 @@ def module_imports_on_top_of_file(
850850
Okay: # this is a comment\nimport os
851851
Okay: '''this is a module docstring'''\nimport os
852852
Okay: r'''this is a module docstring'''\nimport os
853-
Okay: __version__ = "123"\nimport os
853+
Okay: try:\n import x\nexcept:\n pass\nelse:\n pass\nimport y
854+
Okay: try:\n import x\nexcept:\n pass\nfinally:\n pass\nimport y
854855
E402: a=1\nimport os
855856
E402: 'One string'\n"Two string"\nimport os
856857
E402: a=1\nfrom sys import x
@@ -864,6 +865,8 @@ def is_string_literal(line):
864865
line = line[1:]
865866
return line and (line[0] == '"' or line[0] == "'")
866867

868+
allowed_try_keywords = ('try', 'except', 'else', 'finally')
869+
867870
if indent_level: # Allow imports in conditional statements or functions
868871
return
869872
if not logical_line: # Allow empty lines or comments
@@ -873,10 +876,10 @@ def is_string_literal(line):
873876
line = logical_line
874877
if line.startswith('import ') or line.startswith('from '):
875878
if checker_state.get('seen_non_imports', False):
876-
yield 0, "E402 import not at top of file"
877-
elif line.startswith('__version__ '):
878-
# These lines should be included after the module's docstring, before
879-
# any other code, separated by a blank line above and below.
879+
yield 0, "E402 module level import not at top of file"
880+
elif any(line.startswith(kw) for kw in allowed_try_keywords):
881+
# Allow try, except, else, finally keywords intermixed with imports in
882+
# order to support conditional importing
880883
return
881884
elif is_string_literal(line):
882885
# The first literal is a docstring, allow it. Otherwise, report error.

testsuite/E40.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,28 @@
1111

1212
import myclass
1313
import foo.bar.yourclass
14+
#: E402
15+
__all__ = ['abc']
16+
17+
import foo
18+
#: Okay
19+
try:
20+
import foo
21+
except:
22+
pass
23+
else:
24+
print('imported foo')
25+
finally:
26+
print('made attempt to import foo')
27+
28+
import bar
29+
#: E402
30+
VERSION = '1.2.3'
31+
32+
import foo
33+
#: E402
34+
import foo
35+
36+
a = 1
37+
38+
import bar

0 commit comments

Comments
 (0)