47
47
"""
48
48
from __future__ import with_statement
49
49
50
- __version__ = '1.6.0a0'
51
-
52
50
import os
53
51
import sys
54
52
import re
64
62
except ImportError :
65
63
from ConfigParser import RawConfigParser
66
64
65
+ __version__ = '1.6.0a0'
66
+
67
67
DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git,__pycache__,.tox'
68
68
DEFAULT_IGNORE = 'E123,E226,E24,E704'
69
69
try :
@@ -850,7 +850,8 @@ def module_imports_on_top_of_file(
850
850
Okay: # this is a comment\nimport os
851
851
Okay: '''this is a module docstring'''\nimport os
852
852
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
854
855
E402: a=1\nimport os
855
856
E402: 'One string'\n"Two string"\nimport os
856
857
E402: a=1\nfrom sys import x
@@ -864,6 +865,8 @@ def is_string_literal(line):
864
865
line = line [1 :]
865
866
return line and (line [0 ] == '"' or line [0 ] == "'" )
866
867
868
+ allowed_try_keywords = ('try' , 'except' , 'else' , 'finally' )
869
+
867
870
if indent_level : # Allow imports in conditional statements or functions
868
871
return
869
872
if not logical_line : # Allow empty lines or comments
@@ -873,10 +876,10 @@ def is_string_literal(line):
873
876
line = logical_line
874
877
if line .startswith ('import ' ) or line .startswith ('from ' ):
875
878
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
880
883
return
881
884
elif is_string_literal (line ):
882
885
# The first literal is a docstring, allow it. Otherwise, report error.
0 commit comments