使用命名参数,如何告诉接收方方法使用参数的“未提供”版本?在“无”中发送不起作用。以下是我的具体代码,特别注意以下部分:
args=launch[1:] if launch[4] is not None else None
我希望尽可能保持列表理解
procs = [Process(name=key, target=launch[0],
args=launch[1:] if launch[4] is not None else None)
for key, launch in zip(procinfos.keys(), launches)]
结果是选择了one-args版本的进程,然后抱怨args为None:
File "<stdin>", line 15, in parallel
for key, launch in zip(procinfos.keys(), launches)]
File "/usr/lib/python2.7/multiprocessing/process.py", line 104, in __init__
self._args = tuple(args)
TypeError:'NoneType'对象不可迭代
当然有一种蛮力方法:即复制for-comprehension的一部分,并简单地避免指定args =参数。我可能最终会去那条路线......除非另有神奇地出现在这里;)
答案 0 :(得分:2)
默认值args
是一个空元组,而不是None
:
launch[1:] if launch[4] is not None else ()
我真的会避免写三行单行。常规for
循环没有错:
processes = []
for key, launch in zip(procinfos, launches):
args = launch[1:] if launch[4] is not None else ()
process = Process(name=key, target=launch[0], args=args)
processes.append(process)
答案 1 :(得分:2)
您可以使用argument unpacking将命名参数指定为字典,如果args
不存在launch[4] is None
,例如:
procs = []
for key, launch in zip(procinfos.keys(), launches):
params = {"name": key, "target": launch[0]}
if launch[4] is not None:
params["args"] = launch[1:]
procs.append(Process(**params))
答案 2 :(得分:1)
将None
替换为空元组:()
procs = [Process(name=key, target=launch[0],
args=launch[1:] if launch[4] is not None else ())
for key, launch in zip(procinfos.keys(), launches)]