python:S1481 Unused local variables - false positive with type hinting when defining a function

Version used:

  • PyCharm 2020.3 (Professional Edition)
    Build #PY-203.5981.165, built on December 16, 2020
  • SonarLint 4.13.0.24781
  • Python 3.9.1

Code:

def row_col_sep(pair: str) -> list[int]:
    value: str
    return [int(value) for value in pair.split(",")]

SonarLint displays that there’s a code smell “Unused local variables should be removed” for the local varible “value” (see the type hint in line 23 in the attached image), even though the variable is used in the next row.

Hi @minhcccp,

Thank you for reporting this false positive: I created ticket SONARPY-814 to track it.

even though the variable is used in the next row.

Please note that value used at line 24 is not the same variable as the one declared at line 23: list comprehensions in Python 3 define a new scope.

In fact, SonarLint would report a a true positive in the code below.

def row_col_sep(pair: str) -> list[int]:
    value: str = "foo"
    return [int(value) for value in pair.split(",")]

Here value defined in the function scope is definetely not used.

However, I agree that in the code you shared, SonarLint should not report a code smell because

value: str

is not really creating a variable in the function scope and it may be done for documentation purposes.

4 Likes