Skip to content

reduce "python_3000_invalid_escape_sequence" execution time by ~60% #1293

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 33 additions & 26 deletions pycodestyle.py
Original file line number Diff line number Diff line change
Expand Up @@ -1627,6 +1627,29 @@ def ambiguous_identifier(logical_line, tokens):
prev_start = start


# https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
_PYTHON_3000_VALID_ESC = frozenset([
'\n',
'\\',
'\'',
'"',
'a',
'b',
'f',
'n',
'r',
't',
'v',
'0', '1', '2', '3', '4', '5', '6', '7',
'x',

# Escape sequences only recognized in string literals
'N',
'u',
'U',
])


@register_check
def python_3000_invalid_escape_sequence(logical_line, tokens, noqa):
r"""Invalid escape sequences are deprecated in Python 3.6.
Expand All @@ -1637,41 +1660,23 @@ def python_3000_invalid_escape_sequence(logical_line, tokens, noqa):
if noqa:
return

# https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
valid = [
'\n',
'\\',
'\'',
'"',
'a',
'b',
'f',
'n',
'r',
't',
'v',
'0', '1', '2', '3', '4', '5', '6', '7',
'x',

# Escape sequences only recognized in string literals
'N',
'u',
'U',
]

prefixes = []
for token_type, text, start, _, _ in tokens:
if token_type in {tokenize.STRING, FSTRING_START, TSTRING_START}:
if token_type == tokenize.STRING or \
token_type == FSTRING_START or \
token_type == TSTRING_START:
# Extract string modifiers (e.g. u or r)
prefixes.append(text[:text.index(text[-1])].lower())

if token_type in {tokenize.STRING, FSTRING_MIDDLE, TSTRING_MIDDLE}:
if token_type == tokenize.STRING or \
token_type == FSTRING_MIDDLE or \
token_type == TSTRING_MIDDLE:
if 'r' not in prefixes[-1]:
start_line, start_col = start
pos = text.find('\\')
while pos >= 0:
pos += 1
if text[pos] not in valid:
if text[pos] not in _PYTHON_3000_VALID_ESC:
line = start_line + text.count('\n', 0, pos)
if line == start_line:
col = start_col + pos
Expand All @@ -1683,7 +1688,9 @@ def python_3000_invalid_escape_sequence(logical_line, tokens, noqa):
)
pos = text.find('\\', pos + 1)

if token_type in {tokenize.STRING, FSTRING_END, TSTRING_END}:
if token_type == tokenize.STRING or \
token_type == FSTRING_END or \
token_type == TSTRING_END:
prefixes.pop()


Expand Down