多重赋值不匹配¶
ID: py/mismatched-multiple-assignment
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- reliability
- correctness
- types
Query suites:
- python-security-and-quality.qls
赋值语句会评估一个序列表达式,并将序列中的每个项目分配给左侧的某个变量。如果左侧的变量数量与右侧序列中的值数量不匹配,则在运行时会引发异常。
建议¶
确保赋值两侧的变量数量匹配。
示例¶
以下示例显示了斐波那契数列的简单定义。在第一个示例中,赋值中的某个值被重复,导致在运行时引发异常。
# Fibonacci series 1:
# the sum of two elements defines the next
a, b = 0, 1, 1 # Assignment fails: accidentally put three values on right
while b < 10:
print b
a, b = b, a+b
# Fibonacci series 2:
# the sum of two elements defines the next
a, b = 0, 1 # Assignment succeeds: two variables on left and two values on right
while b < 10:
print b
a, b = b, a+b