gpt4 book ai didi

短路时的python调用函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:31 25 4
gpt4 key购买 nike

我有一个函数,它有很多嵌套的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com