WestCoastProjects
WestCoastProjects

Reputation: 63062

How to work with optional parameters that are set to None

With named parameters, how can I tell the receiver method to use the "not supplied" version of the parameter? Sending in None does not work. The following is my specific code, note especially the following portion:

args=launch[1:] if launch[4] is not None else None

I would like if possible to keep the list comprehensions

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

The result is the one-args version of process is selected, and then complains the args is 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' object is not iterable

There is of course a brute-force method: that is to duplicate part of the for-comprehension and simply refrain from specifying the args= parameter. I will probably end up going that route .. unless an alternative magically appears here ;)

Upvotes: 0

Views: 518

Answers (3)

jwodder
jwodder

Reputation: 57480

You can use argument unpacking to specify the named arguments as a dictionary, with args not being present if launch[4] is None, e.g.:

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

Upvotes: 2

Josh Austin
Josh Austin

Reputation: 776

Replace None with an empty Tuple: ()

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

Upvotes: 1

Blender
Blender

Reputation: 298186

The default value of args is an empty tuple, not None:

launch[1:] if launch[4] is not None else ()

I would really avoid writing three-line one-liners. There's nothing wrong with regular for loops:

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)

Upvotes: 2

Related Questions