Skip to content

Update F541 to use new tokens to detect f-strings #7292

@dhruvmanila

Description

@dhruvmanila

F541 checks for useless f-strings i.e., f-strings without any placeholders.

The rule needs to be updated to use the new f-string tokens to detect that.

Possible solution

Once we encounter the FStringStart token and if there are no placeholders inside the f-string, then the next token is guaranteed going to a FStringMiddle token containing the entire content of the f-string and then we'll get the FStringEnd token. For example,

f"we're inside a f-string"

The above code will emit the following tokens:

0 FStringStart 2
2 FStringMiddle {
    value: "we're inside a f-string",
    is_raw: false,
} 25
25 FStringEnd 26

And, for triple-quoted f-strings:

f"""this is a triple
quoted f-string with
multiple lines of text"""

We get the following tokens:

0 FStringStart 4
4 FStringMiddle {
    value: "this is a triple\nquoted f-string with\nmultiple lines of text",
    is_raw: false,
} 64
64 FStringEnd 67

I propose to create two edits:

  1. Remove the f-string prefix. This can be extracted using the FStringStart token
  2. Unescape the f-string using the FStringMiddle token i.e., replacing {{ and }} with { and }

Metadata

Metadata

Assignees

Labels

python312Related to Python 3.12ruleImplementing or modifying a lint rule

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions