locals() 函数返回的字典修改¶
ID: py/modification-of-locals
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- reliability
- correctness
Query suites:
- python-security-and-quality.qls
locals() 函数返回的字典不是函数局部变量的视图,而是副本。因此,修改从 locals() 函数返回的字典不会修改函数的局部变量。
建议¶
如果要修改局部变量,请直接进行操作。
示例¶
在此示例中,不是直接为变量 z 赋值,而是修改了 locals() 函数返回的字典。
def modifies_locals_sum(x, y):
locals()['z'] = x + y
#z will not be defined as modifications to locals() do not alter the local variables.
return z
def fixed_sum(x, y):
z = x + y
return z