Skip to content

Commit 38c0977

Browse files
author
namaevae
committed
this reduces execution time from ~1500 ns to ~1250 ns
1 parent c50ba15 commit 38c0977

File tree

1 file changed

+21
-14
lines changed

1 file changed

+21
-14
lines changed

pycodestyle.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1160,6 +1160,22 @@ def imports_on_separate_lines(logical_line):
11601160
yield found, "E401 multiple imports on one line"
11611161

11621162

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+
11631179
@register_check
11641180
def module_imports_on_top_of_file(
11651181
logical_line, indent_level, checker_state, noqa):
@@ -1178,33 +1194,24 @@ def module_imports_on_top_of_file(
11781194
11791195
Okay: if x:\n import os
11801196
""" # 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')
11901197

11911198
if indent_level: # Allow imports in conditional statement/function
11921199
return
11931200
if not logical_line: # Allow empty lines or comments
11941201
return
11951202
if noqa:
11961203
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 '):
11991205
if checker_state.get('seen_non_imports', False):
12001206
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):
12021208
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):
12041211
# Allow certain keywords intermixed with imports in order to
12051212
# support conditional or filtered importing
12061213
return
1207-
elif is_string_literal(line):
1214+
elif _is_string_literal(logical_line):
12081215
# The first literal is a docstring, allow it. Otherwise, report
12091216
# error.
12101217
if checker_state.get('seen_docstring', False):

0 commit comments

Comments
 (0)