Pass keyword arguments to target function in Python threading.Thread Pass keyword arguments to target function in Python threading.Thread multithreading multithreading

Pass keyword arguments to target function in Python threading.Thread


t = threading.Thread(target=f, kwargs={'x': 1,'y': 2})

this will pass a dictionary with the keyword arguments' names as keys and argument values as values in the dictionary.the other answer above won't work, because the "x" and "y" are undefined in that scope.

another example, this time with multiprocessing, passing both positional and keyword arguments:

the function used being:

def f(x, y, kw1=10, kw2='1'):    pass

and then when called using multiprocessing:

p = multiprocessing.Process(target=f, args=('a1', 2,), kwargs={'kw1': 1, 'kw2': '2'})


You can also just pass a dictionary straight up to kwargs:

import threadingdef f(x=None, y=None):    print x,ymy_dict = {'x':1, 'y':2}t = threading.Thread(target=f, kwargs=my_dict)t.start()