Skip to content

Detect when f-string-syntax is used in a string, but not marked as an f-string #2507

Open
@glasnt

Description

@glasnt

Problem statement

Consider the following codeblock

name = "Katie"

stmt1 = f"Hello {name}"
stmt2 = "Hello {name}"

While the block is correct syntax-wise, the content is almost certainly logically invalid, as seen below:

>>> print(stmt1)
Hello Katie
>>> print(stmt2)
Hello {name}

stmt2 is a valid string, but declares string interpolation formatting that is compatible with f-strings, but the string does not have the f prefix to invoke the interpolation.

Describe the solution you'd like

PyLint should detect strings that use f-string-like syntax, but have not been declared as f-strings, in Python 3.6+

This could either be by:

  • attempting to evaluate the content within {}, and if valid Python, return a warning
  • attempting to evaluate the entire string as an f-string, and if the evaluation does not equal the original string, return a warning

Edge Case One: Having { and } characters are perfectly valid, but on the edge case that the content within them is a reference to an in-scope variable, or some other expression, it is likely the string was meant to be an f-string. This would be desirable to catch as a linting error.

Edge Case Two: f'...' is effectively shorthand for '...'.format(locals()); so this:

mystring = 'hello {name}'
print(mystring.format(name='Katie'))

is entirely legal, and isn't an error. There is a possibly design decision about whether this linting check should be

  • enforced by default
  • enforceable as an option
  • enforceable if the string that triggers the problem doesn't have '.format' invoked on it in the same method.

Additional context

I understand PyLint already warns against f-strings in logging, but I can't locate the base functionality to detect f-strings in the first place. I'd be willing to help implement this feature, but would require some mentoring.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Blocked 🚧Blocked by a particular issueCheckersRelated to a checkerEnhancement ✨Improvement to a componentHacktoberfestHelp wanted 🙏Outside help would be appreciated, good for new contributorsHigh priorityIssue with more than 10 reactions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions