Modification of dictionary returned by locals()¶
ID: py/modification-of-localsKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
The dictionary returned bylocals() is not a view of the function’s locals, but a copy. Therefore, modification of the dictionary returned fromlocals() will not modify the local variables of the function.
Recommendation¶
If the intention is to modify a local variable, then do so directly.
Example¶
In this example, rather than assigning to the variablez directly, the dictionary returned bylocals() is modified.
defmodifies_locals_sum(x,y):locals()['z']=x+y#z will not be defined as modifications to locals() do not alter the local variables.returnzdeffixed_sum(x,y):z=x+yreturnz
References¶
Python Language Reference:The for statement.
Python Tutorial:for statements.