我正在使用 **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'}"
我尝试将这个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
并提供所需的关键字参数?
最佳答案
首先绑定(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)
关于python - 使用 kwargs 执行 Pool.map() 时出现 "TypeError: foo() takes exactly 1 argument",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657724/