Files
codeql/python/ql/src/Statements/ModificationOfLocals.ql
Taus e3688444d7 Python: Also exclude class scope
Changing the `locals()` dictionary actually _does_ change the attributes
of the class being defined, so we shouldn't alert in this case.
2026-04-07 23:46:03 +02:00

45 lines
1.4 KiB
Plaintext

/**
* @name Modification of dictionary returned by locals()
* @description Modifications of the dictionary returned by locals() are not propagated to the local variables of a function.
* @kind problem
* @tags quality
* reliability
* correctness
* @problem.severity warning
* @sub-severity low
* @precision very-high
* @id py/modification-of-locals
*/
import python
private import semmle.python.ApiGraphs
predicate originIsLocals(ControlFlowNode n) {
API::builtin("locals").getReturn().getAValueReachableFromSource().asCfgNode() = n
}
predicate modification_of_locals(ControlFlowNode f) {
originIsLocals(f.(SubscriptNode).getObject()) and
(f.isStore() or f.isDelete())
or
exists(string mname, AttrNode attr |
attr = f.(CallNode).getFunction() and
originIsLocals(attr.getObject(mname))
|
mname in ["pop", "popitem", "update", "clear"]
)
}
from AstNode a, ControlFlowNode f
where
modification_of_locals(f) and
a = f.getNode() and
// in module level scope `locals() == globals()`
// see https://docs.python.org/3/library/functions.html#locals
// FP report in https://github.com/github/codeql/issues/6674
not a.getScope() instanceof Module and
// in class level scope `locals()` reflects the class namespace,
// so modifications do take effect.
not a.getScope() instanceof Class
select a, "Modification of the locals() dictionary will have no effect on the local variables."