python - 使用 kwargs 执行 Pool.map() 时出现 "TypeError: foo() takes exactly 1 argument"

标签 python

我正在使用 **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/

相关文章:

Python 脚本作为 linux 服务/守护进程

python - 如何从我的 python 代码中删除 nan

python - 如何从 gae ndb 查询中获取单个值?

python - Wing IDE 中的 Matlab 样式变量编辑器

python - NaN 会干扰 pandas 中的列连接吗?

python - import matplotlib.pyplot 给出 AttributeError : 'NoneType' object has no attribute 'is_interactive'

python - 在 Fabric 中,如何从另一个 python 文件执行任务?

python - Django - 通过 ForeignKey 属性将参数传递给模型

python - 使用 CountVectorizer 连接自定义功能

通过串口与 Arduino 接口(interface)的 Python 代码无法在 Raspberry Pi 上运行