CodeQL queries 1.25
Skip to end of metadata
Go to start of metadata

Name: Unused local variable

Description: Local variable is defined but not used

ID: py/unused-local-variable

Kind: problem

Severity: recommendation

Precision: very-high

Query: UnusedLocalVariable.ql
/**
 * @name Unused local variable
 * @description Local variable is defined but not used
 * @kind problem
 * @tags maintainability
 *       useless-code
 *       external/cwe/cwe-563
 * @problem.severity recommendation
 * @sub-severity high
 * @precision very-high
 * @id py/unused-local-variable
 */

import python
import Definition

predicate unused_local(Name unused, LocalVariable v) {
  forex(Definition def | def.getNode() = unused |
    def.getVariable() = v and
    def.isUnused() and
    not exists(def.getARedef()) and
    def.isRelevant() and
    not v = any(Nonlocal n).getAVariable() and
    not exists(def.getNode().getParentNode().(FunctionDef).getDefinedFunction().getADecorator()) and
    not exists(def.getNode().getParentNode().(ClassDef).getDefinedClass().getADecorator())
  )
}

from Name unused, LocalVariable v
where
  unused_local(unused, v) and
  // If unused is part of a tuple, count it as unused if all elements of that tuple are unused.
  forall(Name el | el = unused.getParentNode().(Tuple).getAnElt() | unused_local(el, _))
select unused, "The value assigned to local variable '" + v.getId() + "' is never used."

A local variable is defined (by an assignment) but never used.

It is sometimes necessary to have a variable which is not used. These unused variables should have distinctive names, to make it clear to readers of the code that they are deliberately not used. The most common conventions for indicating this are to name the variable _ or to start the name of the variable with unused or _unused.

The query accepts the following names for variables that are intended to be unused:

  • Any name consisting entirely of underscores.
  • Any name containing unused.
  • The names dummy or empty.
  • Any "special" name of the form __xxx__.

Variables that are defined in a group, for example x, y = func() are handled collectively. If they are all unused, then this is reported. Otherwise they are all treated as used.

Recommendation

If the variable is included for documentation purposes or is otherwise intentionally unused, then change its name to indicate that it is unused, otherwise delete the assignment (taking care not to delete right hand side if it has side effects).

Example

In this example, the random_no variable is never read but its assignment has a side effect. Because of this it is important to remove only the left hand side of the assignment in line 10.

import random

def write_random_to_file():
    no = random.randint(1, 10)
    with open("random.txt", "w") as file:
        file.write(str(no))
    return no

def write_random():
    random_no = write_random_to_file()
    print "A random number was written to random.txt"

References