Skip to content

Commit

Permalink
Don't require f-strings when the formatee is a bytestring
Browse files Browse the repository at this point in the history
Fixes #22
  • Loading branch information
akx committed Jul 27, 2022
1 parent d8db1e6 commit e4577d1
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
18 changes: 16 additions & 2 deletions flake8_use_fstring/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import token as _token
import typing as _typing
import re as _re

from tokenize import (
TokenInfo as _TokenInfo,
)
Expand All @@ -10,6 +12,18 @@

Flake8Output = _typing.Tuple[_typing.Tuple[int, int], str]

prefix_re = _re.compile(r"^[^'\"]*")


def is_text_string_token(token: _TokenInfo) -> bool:
if not token.type == _token.STRING:
return False # Not a string at all? Ignore.
# Get the prefix of the string (anything before the first quote)
prefix = prefix_re.match(token.string).group(0).lower()
if 'b' in prefix:
return False # Smells like a bytestring. Ignore it.
return True


class BaseLogicalLineChecker(object):
def __init__(
Expand Down Expand Up @@ -38,7 +52,7 @@ def __iter__(self) -> _typing.Iterator[Flake8Output]:
met_string = False

for i in range(len(self.tokens)):
if self.tokens[i].exact_type == _token.STRING:
if is_text_string_token(self.tokens[i]):
met_string = True

if not self[i]:
Expand All @@ -48,7 +62,7 @@ def __iter__(self) -> _typing.Iterator[Flake8Output]:
# only if last token is string
if i == 0: # cannot use IndexError because -1 is a valid index
continue # pragma: no cover (syntax error)
if self.tokens[i - 1].exact_type != _token.STRING:
if not is_text_string_token(self.tokens[i - 1]):
continue

elif self.greedy == self.GREEDY_MET_STRING:
Expand Down
4 changes: 4 additions & 0 deletions tests/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,9 @@ def format(self): # noqa: A003
'{{m}} {n}'
r'[a-z]{1,3}') # Should not be matched.

# should not be matched on any greedy level < 2
# (bytestrings can't be f-strings)
p = b'%d' % f

# no errors below; coverage
''.strip()
2 changes: 2 additions & 0 deletions tests/test_00.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def test_greedy_2(test_flake8_cmd):
tests/example.py:25:6: FS002 '.format' used
tests/example.py:34:13: FS002 '.format' used
tests/example.py:37:8: FS002 '.format' used
tests/example.py:55:11: FS001 '%' operator used
"""
test_flake8_cmd.test()

Expand All @@ -47,6 +48,7 @@ def test_greedy_different(test_flake8_cmd):
tests/example.py:12:16: FS001 '%' operator used
tests/example.py:15:7: FS001 '%' operator used
tests/example.py:18:12: FS002 '.format' used
tests/example.py:55:11: FS001 '%' operator used
"""
test_flake8_cmd.test()

Expand Down

0 comments on commit e4577d1

Please sign in to comment.