4747"""
4848from __future__ import with_statement
4949
50- __version__ = '1.6.0a0'
51-
5250import os
5351import sys
5452import re
6462except ImportError :
6563 from ConfigParser import RawConfigParser
6664
65+ __version__ = '1.6.0a0'
66+
6767DEFAULT_EXCLUDE = '.svn,CVS,.bzr,.hg,.git,__pycache__,.tox'
6868DEFAULT_IGNORE = 'E123,E226,E24,E704'
6969try :
@@ -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.
0 commit comments