From cb8402add912fa162a42eef9067c446704d919d3 Mon Sep 17 00:00:00 2001 From: Marius Gedminas Date: Thu, 22 Nov 2018 15:13:47 +0200 Subject: Make W605 point to the invalid sequence Instead of having W605 point to the beginning of the string literal, make it point to the precise line and column of the invalid escape sequence. This is more helpful when you have multiline string literals. --- pycodestyle.py | 9 +++++++-- testsuite/W60.py | 13 ++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/pycodestyle.py b/pycodestyle.py index 8b608b0..5b66302 100755 --- a/pycodestyle.py +++ b/pycodestyle.py @@ -1522,7 +1522,7 @@ def python_3000_invalid_escape_sequence(logical_line, tokens): for token_type, text, start, end, line in tokens: if token_type == tokenize.STRING: - orig_start = start + start_line, start_col = start quote = text[-3:] if text[-3:] in ('"""', "'''") else text[-1] # Extract string modifiers (e.g. u or r) quote_pos = text.index(quote) @@ -1535,8 +1535,13 @@ def python_3000_invalid_escape_sequence(logical_line, tokens): while pos >= 0: pos += 1 if string[pos] not in valid: + line = start_line + string[:pos].count('\n') + if line == start_line: + col = start_col + len(prefix) + len(quote) + pos + else: + col = pos - string.rfind('\n', 0, pos) - 1 yield ( - orig_start, + (line, col - 1), "W605 invalid escape sequence '\\%s'" % string[pos], ) diff --git a/testsuite/W60.py b/testsuite/W60.py index 1b03099..4cbaad9 100644 --- a/testsuite/W60.py +++ b/testsuite/W60.py @@ -13,16 +13,23 @@ if x <> 0: x = 0 #: W604 val = `1 + 2` -#: W605:1:9 +#: W605:1:10 regex = '\.png$' -#: W605:1:9 +#: W605:2:1 regex = ''' \.png$ ''' -#: W605:2:5 +#: W605:2:6 f( '\_' ) +#: W605:4:6 +""" +multi-line +literal +with \_ somewhere +in the middle +""" #: Okay regex = r'\.png$' regex = '\\.png$' -- cgit v1.2.1 From e5a057982bfd68cd825eeea6bd8dce5bc0759e9f Mon Sep 17 00:00:00 2001 From: Marius Gedminas Date: Thu, 22 Nov 2018 15:17:40 +0200 Subject: Microoptimisation: avoid creating string slices str.count() can limit the counting to a range of string positions. --- pycodestyle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pycodestyle.py b/pycodestyle.py index 5b66302..f0ae6dc 100755 --- a/pycodestyle.py +++ b/pycodestyle.py @@ -1535,7 +1535,7 @@ def python_3000_invalid_escape_sequence(logical_line, tokens): while pos >= 0: pos += 1 if string[pos] not in valid: - line = start_line + string[:pos].count('\n') + line = start_line + string.count('\n', 0, pos) if line == start_line: col = start_col + len(prefix) + len(quote) + pos else: -- cgit v1.2.1