0

使用命名参数,我如何告诉接收器方法使用参数的“未提供”版本?发送 None 不起作用。以下是我的具体代码,特别注意以下部分:

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)]

结果是选择了单参数版本的进程,然后抱怨 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”对象不可迭代

当然有一种蛮力方法:即复制部分理解并简单地避免指定 args= 参数。我可能最终会走那条路..除非在这里神奇地出现替代方案;)

4

3 回答 3

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)
于 2013-05-15T22:28:25.837 回答
2

您可以使用参数解包将命名参数指定为字典,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))
于 2013-05-15T22:32:57.150 回答
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)]
于 2013-05-15T22:31:47.300 回答