例如,给定
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")
,请注意,即使next
调用在第二次调用时短路且输出为“ bc”,也会打印“ d”。
我正在对列表a
中的呼叫进行硬编码,并且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是类似的问题,但仅在函数具有相同的方法签名时才适用。
您可以将它们全部放入函数中并产生结果:
def gen():
yield expensive_call("a")
yield expensive_call_2("b", "c")
yield expensive_call("d")
result = next(
(value for value in gen() if value is not None),
'All are Nones')
另一个解决方案是使用partial
应用程序:
partial
然后评估:
from functools import partial
calls = [partial(expensive_call, 'a'),
partial(expensive_call_2, 'b', 'c'),
partial(expensive_call, 'd')]
您可以使用以下装饰器:
next((result for call in calls
for result in [call()]
if result is not None),
'All results None')
((如果您喜欢lambda,也可以表示为def lazy_fn(fn):
return lambda *args: lambda: fn(*args)
。]
像这样使用它:
lazy_fn = lambda fn: lambda *args: lambda: fn(*args)
输出:
@lazy_fn
def expensive_call(x):
print(x)
if x == "d":
return x
@lazy_fn
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")]
print(next((e for e in map(lambda i: i(), a) if e is not None), 'All are Nones'))
请注意,您无需使用a
b
c
bc
,而需要使用for e in a
。