我有一个函数,它有很多嵌套的 if 语句,sonarqube 提示它。可能会发生一系列情况,我会跟踪每种情况发生的时间,返回一个 bool 和一个 int,然后增加一个计数器。
def _fix(ids, id, sch_date, cycles, dp):
try:
gs = cycles.get(id)
except AttributeError:
gs = False
if id in ids:
if cycles:
if gs:
if sch_date in gs:
if dp in gs[sch_date]:
return True, None
else:
self.d_types[4] += 1
return False, 4
else:
self.d_types[1] += 1
return False, 1
else:
self.d_types[3] += 1
return False, 3
else:
self.d_types[2] += 1
return False, 2
else:
return False, None
我在想我可以做这样的事情:
if id in ids and cycles and gs and such_date in gs and dp in gs[sch_date]:
do something...
但是我不知道它在哪里短路,所以我将无法增加计数器或返回必要的 int 和 boolean。
有什么想法可以摆脱所有这些 if 语句,同时仍然保留 return 和 counter 吗?
最佳答案
每个 else
都可以终止函数,因此反转测试条件。如果函数已经返回,则不需要 else
,这大大减少了嵌套代码。
if id not in ids:
return False, None
if not cycles:
self.d_types[2] += 1
return False, 2
if not gs:
self.d_types[3] += 1
return False, 3
if sch_date not in gs:
self.d_types[1] += 1
return False, 1
if dp not in gs[sch_date]:
self.d_types[4] += 1
return False, 4
return True, None
关于短路时的python调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37128841/