Skip to content

Commit 691b8a5

Browse files
pynicolasalban-auzeill
authored andcommitted
SONARPY-228 Fix FP in UnusedLocalVariableCheck when "locals()" is used (SonarSource#117)
1 parent 481ff20 commit 691b8a5

3 files changed

Lines changed: 16 additions & 6 deletions

File tree

its/ruling/src/test/resources/expected/python-S1481.json

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -166,12 +166,6 @@
166166
'project:django-1.4/django/core/cache/__init__.py':[
167167
133,
168168
],
169-
'project:django-1.4/django/db/backends/oracle/base.py':[
170-
93,
171-
94,
172-
95,
173-
96,
174-
],
175169
'project:django-1.4/django/db/backends/sqlite3/creation.py':[
176170
84,
177171
],

python-checks/src/main/java/org/sonar/python/checks/UnusedLocalVariableCheck.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,22 @@ public Set<AstNodeType> subscribedKinds() {
4040

4141
@Override
4242
public void visitNode(AstNode functionTree) {
43+
// https://docs.python.org/3/library/functions.html#locals
44+
if (isCallingLocalsFunction(functionTree)) {
45+
return;
46+
}
4347
for (Symbol symbol : getContext().symbolTable().symbols(functionTree)) {
4448
checkSymbol(symbol);
4549
}
4650
}
4751

52+
private static boolean isCallingLocalsFunction(AstNode functionTree) {
53+
return functionTree
54+
.getDescendants(PythonGrammar.NAME)
55+
.stream()
56+
.anyMatch(node -> "locals".equals(node.getTokenValue()));
57+
}
58+
4859
private void checkSymbol(Symbol symbol) {
4960
if (symbol.readUsages().isEmpty()) {
5061
for (AstNode writeUsage : symbol.writeUsages()) {

python-checks/src/test/resources/checks/unusedLocalVariable.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,8 @@ def f(unread_param):
1010
read_in_nested_function = 1
1111
def nested_function():
1212
print(read_in_nested_function)
13+
14+
def using_locals(a, b):
15+
c = a + b
16+
# "locals" will include the "c" value
17+
return locals()

0 commit comments

Comments
 (0)