Put target function's named arguments into multiprocessing.Process with key=value syntax
Question:
We have a standard function syntax for passing keyword arguments. We can call foo(arg_1=value1, arg_2=value2)
and this works well. But it doesn’t work when I try to put arguments into multiprocessing.Process
.
This expression multiprocessing.Process(target=foo, args=(arg_1=value1, arg_2=value2))
causes exception:
SyntaxError: invalid syntax
How can I put ‘named’ arguments into the process (to avoid data entering error)?
Answers:
multiprocessing.Process
expects a tuple as the args
argument which is passed as positional arguments to the target
function. If you want to pass keyword arguments to target
, you have to provide a dictionary as the kwargs
argument to multiprocessing.Process
.
If you want to use the key=value
syntax, instead of providing a dictionary literal {'arg1': value1, 'arg2': value2}
you can use the dict()
constructor:
multiprocessing.Process(target=foo, kwargs=dict(arg_1=value1, arg_2=value2))
Note that it has some limitations, see What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?
We have a standard function syntax for passing keyword arguments. We can call foo(arg_1=value1, arg_2=value2)
and this works well. But it doesn’t work when I try to put arguments into multiprocessing.Process
.
This expression multiprocessing.Process(target=foo, args=(arg_1=value1, arg_2=value2))
causes exception:
SyntaxError: invalid syntax
How can I put ‘named’ arguments into the process (to avoid data entering error)?
multiprocessing.Process
expects a tuple as the args
argument which is passed as positional arguments to the target
function. If you want to pass keyword arguments to target
, you have to provide a dictionary as the kwargs
argument to multiprocessing.Process
.
If you want to use the key=value
syntax, instead of providing a dictionary literal {'arg1': value1, 'arg2': value2}
you can use the dict()
constructor:
multiprocessing.Process(target=foo, kwargs=dict(arg_1=value1, arg_2=value2))
Note that it has some limitations, see What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?