我为functools.partial
的函数创建**kwargs
。
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'}"
我尝试将此partial
作为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
并提供所需的关键字参数?
答案 0 :(得分:3)
首先绑定位置参数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)