@@ -1160,6 +1160,22 @@ def imports_on_separate_lines(logical_line):
1160
1160
yield found , "E401 multiple imports on one line"
1161
1161
1162
1162
1163
+ _STRING_PREFIXES = frozenset (('u' , 'U' , 'b' , 'B' , 'r' , 'R' ))
1164
+
1165
+
1166
+ def _is_string_literal (line ):
1167
+ if line :
1168
+ first_char = line [0 ]
1169
+ if line [0 ] in _STRING_PREFIXES :
1170
+ first_char = line [1 ]
1171
+ return first_char == '"' or first_char == "'"
1172
+ return False
1173
+
1174
+
1175
+ _ALLOWED_KEYWORDS_IN_IMPORTS = frozenset ([
1176
+ 'try' , 'except' , 'else' , 'finally' , 'with' , 'if' , 'elif' ])
1177
+
1178
+
1163
1179
@register_check
1164
1180
def module_imports_on_top_of_file (
1165
1181
logical_line , indent_level , checker_state , noqa ):
@@ -1178,33 +1194,24 @@ def module_imports_on_top_of_file(
1178
1194
1179
1195
Okay: if x:\n import os
1180
1196
""" # noqa
1181
- def is_string_literal (line ):
1182
- if line [0 ] in 'uUbB' :
1183
- line = line [1 :]
1184
- if line and line [0 ] in 'rR' :
1185
- line = line [1 :]
1186
- return line and (line [0 ] == '"' or line [0 ] == "'" )
1187
-
1188
- allowed_keywords = (
1189
- 'try' , 'except' , 'else' , 'finally' , 'with' , 'if' , 'elif' )
1190
1197
1191
1198
if indent_level : # Allow imports in conditional statement/function
1192
1199
return
1193
1200
if not logical_line : # Allow empty lines or comments
1194
1201
return
1195
1202
if noqa :
1196
1203
return
1197
- line = logical_line
1198
- if line .startswith ('import ' ) or line .startswith ('from ' ):
1204
+ if logical_line .startswith ('import ' ) or logical_line .startswith ('from ' ):
1199
1205
if checker_state .get ('seen_non_imports' , False ):
1200
1206
yield 0 , "E402 module level import not at top of file"
1201
- elif re .match (DUNDER_REGEX , line ):
1207
+ elif re .match (DUNDER_REGEX , logical_line ):
1202
1208
return
1203
- elif any (line .startswith (kw ) for kw in allowed_keywords ):
1209
+ elif any (logical_line .startswith (kw )
1210
+ for kw in _ALLOWED_KEYWORDS_IN_IMPORTS ):
1204
1211
# Allow certain keywords intermixed with imports in order to
1205
1212
# support conditional or filtered importing
1206
1213
return
1207
- elif is_string_literal ( line ):
1214
+ elif _is_string_literal ( logical_line ):
1208
1215
# The first literal is a docstring, allow it. Otherwise, report
1209
1216
# error.
1210
1217
if checker_state .get ('seen_docstring' , False ):
0 commit comments