短路时的python调用函数

标签 python

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

相关文章:

python - Django休息框架: how to get the current superuser in serialize?

python - Django 模型设计 - 多对多字段

python - ZeroMQ:如何在 python 和 Node 之间保持 PAIR/PAIR 的连接?

python - 如何从子函数将模块导入 main()?

python - 元素当前不可见,因此可能无法与之交互,Selenium Dropdown Box Python

python - 使用 Regex 将每个匹配实例替换为不同的字符串

将哈希值生成为数字的 Python 库

python - 我想从字典中得到两个最小的数字

python - Scrapy-Splash:无法使用 scrapinghub/splash:latest 作为基础镜像运行 docker 容器

python - 相当于 python 在 golang 中的 utils.execute()