循环中不必要的“else”子句¶
ID: py/redundant-else
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- maintainability
- useless-code
Query suites:
- python-security-and-quality.qls
循环(无论是 for
还是 while
语句)的 else
子句在循环正常终止后立即执行。如果循环体内有 break
语句,则跳过 else
子句。如果没有 break
语句,则 else
子句将在循环结束后始终执行,除非它使用 return
或 raise
退出。因此,如果循环体内没有 break
语句,则可以使用未缩进的代码替换 else
子句。
通常应尽量避免使用 else
子句,因为它们可能会被误解。
建议¶
使用未缩进的代码替换 else
子句。
示例¶
在本例中,pointless_else
函数包含一个冗余的 else
子句。可以简化 else
子句,如 no_else
函数所示,该函数具有相同的语义,但没有 else
子句。第三个示例函数 with_break
显示了 else
子句必须存在的情况,因为 break
语句会跳过 else
子句。
def pointless_else(container):
for item in container:
if of_interest(item):
return item
else:
raise NotFoundException()
def no_else(container):
for item in container:
if of_interest(item):
return item
raise NotFoundException()
def with_break(container):
for item in container:
if of_interest(item):
found = item
break
else:
raise NotFoundException()
return found
参考¶
Python 语言参考:The while statement.
Python 教程:Break and continue statements, and else clauses on loops.