python future和tuple unpacking

时间:2017-09-21 02:58:20

标签: python future dask iterable-unpacking concurrent.futures

使用期货来实现像元组拆包这样的东西是什么样的优雅/惯用方式?

我有像

这样的代码
a, b, c = f(x)
y = g(a, b)
z = h(y, c)

我希望将其转换为使用期货。 理想情况下,我想写一些类似

的内容
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

虽然。 如何在不必再拨打3个a,b,c电话的情况下获取ex.submit?即。我想避免写这个:

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

1 个答案:

答案 0 :(得分:2)

快速浏览一下:

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)的结果。

这个答案表明链接期货不是微不足道的:

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