gpt4 book ai didi

python - 如何优雅地将 'reasons' 与返回值耦合

转载 作者:行者123 更新时间:2023-11-28 19:40:47 24 4
gpt4 key购买 nike

在我编写的代码中经常发生的事情是我将有一个函数来检查依赖于许多其他条件的条件,例如:

def is_foo(bar):
if X: return True
if Y: return False
if Z: return True
return False

然后,我想调试我的代码或记录它,所以我将上面的更改为:

def is_foo_reason(bar):
if X: return True, "cause of X you fool"
if Y: return False, "no X but Y"
if Z: return True, "Z Z Z Z Z Z"
return False, "default"
#for backwards compatibility:
def is_foo(bar): return is_foo_reason(bar)[0]

然后需要原因的代码(以便它可以记录它/向用户显示它,w/e)调用 _reason 版本。

我的问题是:有没有更优雅的方法来做到这一点?

最佳答案

这是一个非常好的方法。我唯一可能改变的是在 is_foo 中嵌套 is_foo_reason(这样只有一个简单的接口(interface))并向 is_foo() 添加一个默认参数,例如

#for backwards compatibility:
def is_foo(bar, reason=False):
def is_foo_reason(bar):
if X: return True, "cause of X you fool"
if Y: return False, "no X but Y"
if Z: return True, "Z Z Z Z Z Z"
return False, "default"
if reason:
return is_foo_reason(bar)
else:
return is_foo_reason(bar)[0]

那样的话,默认情况下函数不会给出原因,但如果你想要一个,你可以要求一个。

关于python - 如何优雅地将 'reasons' 与返回值耦合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6446603/

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