在我写的代码中经常发生的事情是我将有一个函数来检查依赖于许多其他条件的条件,例如:
def is_foo(bar):
if X: return True
if Y: return False
if Z: return True
return False
Run Code Online (Sandbox Code Playgroud)
然后,我想调试我的代码或记录它,所以我将上面改为:
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]
Run Code Online (Sandbox Code Playgroud)
然后,想要原因的代码(因此它可以将其记录/显示给用户,w/e)调用该_reason
版本.
我的问题是:有没有更优雅的方式来做到这一点?
这是一个非常好的方法.只有我可能会改变的是窝is_foo_reason
在is_foo
(所以只有一个,简单的界面),并添加默认的参数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]
Run Code Online (Sandbox Code Playgroud)
这样,默认情况下该功能不会给出原因,但如果你想要一个,你可以要求一个.
归档时间: |
|
查看次数: |
83 次 |
最近记录: |