Skip to main content
 首页 » 编程设计

python future 和元组解包

2024年10月01日7Leo_wl

什么是优雅/惯用的方式来实现元组解包之类的功能?

我有这样的代码

a, b, c = f(x) 
y = g(a, b) 
z = h(y, c) 

我想将其转换为使用 future 。 理想情况下,我想写一些类似的东西

a, b, c = ex.submit(f, x) 
y = ex.submit(g, a, b) 
z = ex.submit(h, y, c) 

第一行抛出

TypeError: 'Future' object is not iterable 

虽然。 我怎样才能获得 a,b,c 而不必进行 3 个额外的 ex.submit 调用? IE。我想避免将其写成:

import operator as op 
fut = ex.submit(f, x) 
a = client.submit(op.getitem, fut, 0) 
b = client.submit(op.getitem, fut, i) 
c = client.submit(op.getitem, fut, 2) 
y = ex.submit(g, a, b) 
z = ex.submit(h, y, c) 

我想一个潜在的解决方案是编写一个如下所示的 unpack 函数,

import operator as op 
def unpack(fut, n): 
    return [client.submit(op.getitem, fut, i) for i in range(n)] 
 
a, b, c = unpack(ex.submit(f, x), 3) 
y = ex.submit(g, a, b) 
z = ex.submit(h, y, c) 

有效:例如,如果您首先定义:

def f(x): 
    return range(x, x+3) 
x = 5 
g = op.add 
h = op.mul 

然后你得到

z.result() #===> 77 

我认为这样的东西可能已经存在了。


以上仅适用于 dask.distributed.Future。它不适用于普通 concurrent.futures.Future。

请您参考如下方法:

快速浏览:

https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future

建议你必须做类似的事情

afuture = ex.submit(f, x) 
a,b,c = afuture.result() 
... 

submit 返回一个 Future 对象,而不是运行 f(x) 的结果。

这个 SO 答案表明链接 future 并非微不足道:

How to chain futures in a non-blocking manner? That is, how to use one future as an input in another future without blocking?