Remove the unused local variable - Pandas query false positives


I’m using SonarCloud for Python via AzureDevOps pipelines and I get a lot of false positive ‘unused local variable’ hits for referencing variables using the ‘@’ notation in a Pandas dataframe query.

src: pandas.DataFrame.query — pandas 1.4.4 documentation
You can refer to variables in the environment by prefixing them with an ‘@’ character like @a + b.

Considering the above is a valid Python, referencing variables with the ‘@’ character in query strings should not cause an ‘unused local variable’ code smell. It is very annoying to have to mark tens of code smells as false positives every single time.

Some sample code that should reproduce the issue:

import pandas as pd

d = {'area': ['fictional_town', 'fictional_city'], 'population': [100, 2000]}
sample_df = pd.DataFrame(data=d)

area_of_interest = 'fictional_city'
pop = sample_df.query('area == @area_of_interest').population

Hopefully this can be resolved somehow or is there a work around to prevent this from being flagged?

Hi @nobelv ,

First of all, sorry for the late reply and thanks a lot for reporting those false positives.

We are considering supporting pandas query strings in a future sprint in our analyzer, to be able to detect variables usages , like @area_of_interest in the example you provided.

Note that “unused local variable” rule (S1481) is not the only one impacted: other rules like “unused assignments should be removed” (S1854) are affected by the lack of support of pandas query strings.

I created ticket SONARPY-1166 to keep track of it.

The only workaround I can suggest at the moment is to disable rule S1481 about “unused local variable” from your quality profile.

EDIT: Another possible workaround is to exclude rules where you’re having FPs (like S1481) from specific files / patterns. You can have a look at the documentation here for SonarCloud and here for SonarQube (section Only apply specific rules to specific files)

Hope that helps,