潜在未初始化的局部变量¶
ID: py/uninitialized-local-variable
Kind: problem
Security severity:
Severity: error
Precision: medium
Tags:
- reliability
- correctness
Query suites:
- python-security-and-quality.qls
此局部变量可能在定义之前使用。如果在函数中将变量赋值,并且未显式声明 global
或 nonlocal
,则假定它是局部变量。如果在定义之前使用它,则会引发 UnboundLocalError
。
建议¶
查看代码并考虑变量的预期范围。确定变量应该是全局还是局部范围。如果需要全局变量,则添加 global
语句,或者在 Python 3 中,如果变量出现在封闭函数中,则可以使用 nonlocal
语句。否则,确保在使用变量之前定义它。
示例¶
以下代码包含使用变量的不同函数。 test1()
失败并引发 UnboundLocalError
,因为在初始化之前使用了局部变量 var
。
def test():
var = 1
def print_var():
print var # Use variable from outer scope
print_var()
print var
def test1():
var = 2
def print_var():
print var # Attempt to use variable from local scope.
var = 3 # Since this is not initialized yet, this results
print_var() # in an UnboundLocalError
print var
def test2():
var = 2
def print_var():
var = 3 # Initialize local version of the variable
print var # Use variable from local scope.
print_var() # Note that this local variable "shadows" the variable from
print var # outer scope which makes code more difficult to interpret.
def test3():
var = 4
def print_var():
nonlocal var # Use non-local variable from outer scope.
print var
print_var()
print var
参考¶
Python 标准库:内置异常:UnboundLocalError。
Python 常见问题解答:为什么我在变量有值时会收到 UnboundLocalError?。
Python 课程:全局变量和局部变量。
Python 语言参考:global 语句,nonlocal 语句。