Python S1481 Unused local variables false positive with f-string format specifications

Versions used:

  • SonarQube 8.1
  • SonarPython 2.8 (build 6204)

Code:

def main():
    """Test variable f-string padding."""
    minlen = 10
    sline = f"{'padded':{minlen}} string "
    sline += f"{3.14159265358979:.{minlen}}"
    return sline

Output (padded string and truncated pi):

padded     string 3.141592654

SonarQube will complain than minlen is unused and should be removed:

SonarLint: Remove the unused local variable “minlen”.

This is a false positive, because minlen is used as a nested format specification of the f-strings.

(This is a minimal working example. The value of minlen is computed in our actual code and can thus not be replaced with a constant.)

Edit: Clarified that it is a nested format specification. From the link above:

A format_spec field can also include nested replacement fields within it.

It seems that these nested fields are not counted as code.

1 Like

Hi @hugobuddel,
Welcome to our community and thank you for reporting this false positive.
I created the following ticket to keep track of it: https://jira.sonarsource.com/browse/SONARPY-699

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.