Skip to content

Commit 373e0ac

Browse files
committed
Allow try/except/else/finally keywords intermixed with imports. #304
* This allows use of conditional imports. * Also move `__version__` definition to conform with this rule.
1 parent 53d4741 commit 373e0ac

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

pep8.py

Lines changed: 9 additions & 6 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
@@ -874,9 +877,9 @@ def is_string_literal(line):
874877
if line.startswith('import ') or line.startswith('from '):
875878
if checker_state.get('seen_non_imports', False):
876879
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.
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.

0 commit comments

Comments
 (0)