Unused Local Variable

ID

python.unused_local_variable

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Dead Code

Language

Python

Tags

CWE:563, dead-code, reliability

Description

Reports a local-variable binding that is never read. The flagged form is a plain name = value assignment inside a function body, plus the local bindings introduced by for …​ as name, with …​ as name, and except …​ as name. By Python convention, intentional throwaway bindings are spelled with a leading underscore (_unused) — the rule honours that convention.

def f():
    x = compute()              # FLAW — never read
    return 0

def g():
    for i in range(10):        # FLAW on i — convention: use _
        do_work()

def h():
    y = 1                      # OK — read below
    return y

def i():
    _unused = compute()        # OK — leading underscore is intentional
    return 0

Module-level bindings, class-level fields, and function parameters are out of scope (covered by python.unused_method_parameter for the latter).

Rationale

Unused locals fall into two camps: leftover from a refactor that nobody removed, or a typo that is silently masking a bug (the writer assigned to the wrong name). Either way, they are noise — and the bug-of-typo case is worth catching at review time.

Remediation

  • Delete the assignment if the value is never needed.

  • Rename the binding to _name if the side-effect is what you actually wanted.

  • If the value is meant to be read, look for the typo that left it dangling.