尝试-考虑-else (TRY300)
源自 tryceratops linter。
作用
检查try
块中的return
语句。
为什么这不好?
try
-except
语句有一个else
子句,用于仅在未引发异常时运行的代码。try
块中的返回语句可能会表现出令人困惑或不希望的行为,例如被except
和finally
块中的控制流覆盖,或无意中抑制异常。
示例
import logging
def reciprocal(n):
try:
rec = 1 / n
print(f"reciprocal of {n} is {rec}")
return rec
except ZeroDivisionError:
logging.exception("Exception occurred")
建议改为
import logging
def reciprocal(n):
try:
rec = 1 / n
except ZeroDivisionError:
logging.exception("Exception occurred")
else:
print(f"reciprocal of {n} is {rec}")
return rec