如果你担心被调用,而不是仅仅被评估的变量B或C的存在功能,那么这段代码表明,短路是你的朋友:
a = False
def b():
print "b was called"
return True
if a and b():
print "this shouldn't happen"
else:
print "if b was not called, then short-circuiting works"
打印
if b was not called, then short-circuiting works
但如果你有代码,这是否:
a = call_to_expensive_function_A()
b = call_to_expensive_function_B()
c = call_to_expensive_function_C()
if a and b and c:
do something...
那么你的代码是STIL l调用所有3个昂贵的函数。最好让Python成为Python:
if (call_to_expensive_function_A() and
call_to_expensive_function_B() and
call_to_expensive_function_C())
do something...
它只会调用尽可能多的昂贵的函数来确定整体条件。
# note, this is a list of the functions themselves
# the functions are *not* called when creating this list
funcs = [function_A, function_B, function_C]
if all(fn() for fn in funcs):
do something
现在,如果你需要添加其他功能,或者希望重新排序(也许function_A
是非常耗时:
编辑
您可以在此使用all
内置推广消耗,并且您将通过筛选首先失败function_B
或function_C
的案例受益),那么您只需更新funcs
列表。 all
确实发生短路,就好像你已经将if写成if a and b and c
一样。 (如果功能一起使用,则使用any
内建代替。)
同意。不要担心性能,担心可读性。就像Martin Fowler说的那样:“任何傻瓜都可以编写计算机可以理解的代码......但只有好的程序员才能编写人类可以理解的代码。” – 2010-03-29 17:21:14
如果您怀疑自己有性能问题,首先要做的就是测量代码的速度。然后编写你的替代版本,测量它,并看看你的改变是否真的让代码更快。 * Code Complete *中有一个很棒的部分。 – 2010-03-29 17:22:03