我正在为一个带有 **kwargs 的函数创建一个 functools.partial。
from functools import partial
def foo(required, **kwargs):
return required + str(kwargs)
_foo = partial(foo, "hello", bar='baz')
foo("hello", bar='baz') 和 _foo() 都打印了预期的输出:
In [4]: foo("hello", bar="baz")
Out[4]: "hello{'bar': 'baz'}"
In [5]: _foo()
Out[5]: "hello{'bar': 'baz'}"
我尝试将此部分 作为multiprocessing.Pool 的一部分运行:
import multiprocessing as mp
pool = mp.Pool()
results = pool.map(_foo, range(2)) # Run the _foo partial twice
但是我得到:
TypeError: foo() takes exactly 1 argument (3 given)
如何在池中执行 foo 并提供所需的关键字参数?
请您参考如下方法:
您首先绑定(bind)位置参数 required,然后在 map 调用中,隐式传递另一个位置参数(第一次调用为 0,第二次调用为 1)。
当然,这些都是无效调用,无论池如何,都可以很容易地证明这一点:
_foo = partial(foo, "hello", bar='baz') # required is bound to "hello" here
_foo(0) # no more position arguments are allowed...
=> TypeError: foo() takes exactly 1 argument (3 given)
