Skip to content

Instantly share code, notes, and snippets.

@moreati
Last active December 19, 2017 23:13
Show Gist options
  • Save moreati/300463f8575a4eafc0271e72a3784782 to your computer and use it in GitHub Desktop.
Save moreati/300463f8575a4eafc0271e72a3784782 to your computer and use it in GitHub Desktop.
Pylint plugin that checks for non f-string literals, with format() style string interpolation
import re
import tokenize
import astroid
from pylint.checkers import BaseChecker, BaseTokenChecker
from pylint.interfaces import IAstroidChecker, ITokenChecker
FORMAT_PATT = re.compile(r'\$\{.*?}')
class FStringChecker(BaseTokenChecker):
"""
Check that string literals containing interpolation are an f-string.
"""
__implements__ = ITokenChecker
name = 'fstring-literal'
msgs = {
'W0001': (
'Contains string interpolation, but is not an f-string.',
'non-fstring-literal',
'All interpolated string literals should be f-strings.'
),
}
def process_tokens(self, tokens):
for tok_type, token, (start_row, _), _, _ in tokens:
if tok_type == tokenize.STRING:
self._process_string_token(token, start_row)
def _process_string_token(self, token, start_row):
if token[0] == 'f':
return
if not FORMAT_PATT.search(token):
return
self.add_message(
'non-fstring-literal',
line=start_row,
)
def register(linter):
linter.register_checker(FStringChecker(linter))
"""A demonstration file for fstring_checker.py"""
WITH_F = 'foo'
print('${without_f}')
print('${without_f_ignored}') # pylint: disable=non-fstring-literal
print(f'${WITH_F}')
@moreati
Copy link
Author

moreati commented Dec 19, 2017

Call it with

$ PYTHONPATH=. pylint --load-plugins fstring_checker fstring_checker_demo.py 
No config file found, using default configuration
************* Module fstring_checker_demo
W:  5, 0: Contains string interpolation, but is not an f-string. (non-fstring-literal)

------------------------------------------------------------------
Your code has been rated at 7.50/10 (previous run: 5.00/10, +2.50)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment