Last active
December 19, 2017 23:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)