例如,给定
def expensive_call(x):
print(x)
if x == "d":
return x
def expensive_call_2(x, y):
print(x)
print(y)
return x + y
a = [expensive_call("a"), expensive_call_2("b", "c"), expensive_call("d")]
next((e for e in a if e is not None), 'All are Nones')
输出是
a
b
c
d
Out[22]: 'bc'
自从
expensive_call("d")
被热切地评价,注意“d”被打印即使
next
第二次呼叫时呼叫短路,输出为“BC”。
我把名单上的电话都硬编码了
a
和
一
不必是列表数据结构。
一种可能的解决方案如下:
a = ['expensive_call("a")', 'expensive_call_2("b", "c")', 'expensive_call("d")']
def generator():
for e in a:
r = eval(e)
if r is not None:
yield r
next(generator(), 'All are Nones')
输出是
a
b
c
Out[23]: 'bc'
如所愿。但是,我不喜欢使用eval。我也不希望使用任何一个最初将函数指针和参数分开的解决方案
(expensive_call, ("a"))
. 理想情况下我会有
a = lazy_magic([expensive_call("a"), expensive_call_2("b", "c"), expensive_call("d")])
next((e for e in a if e is not None), 'All are Nones')
请注意
https://stackoverflow.com/a/3405828/2750819
是一个类似的问题,但仅适用于函数具有相同方法签名的情况。