SCR118: used-before-assignment
Variable is read where no assignment can have happened
| Code | SCR118 |
| Name | used-before-assignment |
| Category | Scripts (SCR) |
| Default severity | error |
| Enabled by default | yes |
| Fix available | no |
| ign-lint equivalent | none |
What it does
Section titled “What it does”Reports reads of a function's local variable (or a module-level name in
module code) that no assignment reaches on any path: it is read before its
first assignment, after del, or only assigned in a branch that cannot
run. The analysis follows if/else, loops (a later iteration sees
earlier assignments), try/except/else/finally, with, break,
continue, return and raise. A variable that is assigned on at least
one path is never reported: the rule only reports reads that fail every
time they run.
A name is local to a function when the function assigns it anywhere, even
after the read; then a module-level variable of the same name is not
visible in the function (Python raises UnboundLocalError).
Unreachable reads, scopes with exec or from x import *, and reads in a
try that catches NameError are not reported. Module-level reads fall
back to builtins and to names that functions bind with global.
Why is this bad?
Section titled “Why is this bad?”The read raises UnboundLocalError (functions) or NameError (module
code) every time it runs.
Example
Section titled “Example”COUNTER = 0
def onMessageReceived(self, payload): COUNTER += 1 self.custom.count = COUNTERUse instead:
def onMessageReceived(self, payload): self.custom.count = (self.custom.count or 0) + 1pylint
Section titled “pylint”Corresponds to E0601 used-before-assignment (definite cases only;
pylint's possibly-used-before-assignment is not reported). pylint misses
the augmented assignment case (N += 1 in a function where N is a
module variable), which always raises UnboundLocalError.
Generated from the rule metadata by iglint generate-docs; iglint rule SCR118 prints the same page in the terminal. Source: docs/rules/SCR118.md.