Search code examples
pythondebuggingpylint

How to check python scripts for f-strings which are missing the f literal? (for pre-debugging / lint)


I often forget to prefix formatted strings with "f".

A buggy example: text = "results is {result}"
Where it should be text = f"results is {result}"

I make this error A LOT; my IDE don't report it, and the program runs without exceptions.

I thought maybe to scan my source code for quoted strings, check for {,} characters, and search if it's missing a prefix "f" literal;

But it's better, i guess, to use a parser? Or maybe someone did it already?


Solution

  • The problem is that text = "results is {result}" is a valid template string, so you can later use it in your program like:

    >>> text.format(result=1)
    'results is 1'
    >>> text.format(result=3)
    'results is 3'
    

    What you can achieve is just checking if an f-string does indeed use variables inside, like pylint and flake8 already do.

    For what you seek, however, there is something going on with PyLint: this issue is 3 years old, but it is exactly what you need, and recently - three days ago - an user submitted a pull request that is currently WIP, and should resolve your problem.