Pass keyword arguments to target function in Python threading.Thread

PythonMultithreadingPython 2.7Python MultithreadingKeyword Argument

Python Problem Overview


I want to pass named arguments to the target function, while creating a Thread object.

Following is the code that I have written:

import threading

def f(x=None, y=None):
    print x,y

t = threading.Thread(target=f, args=(x=1,y=2,))
t.start()

I get a syntax error for "x=1", in Line 6. I want to know how I can pass keyword arguments to the target function.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

import threading

def f(x=None, y=None):
    print x,y

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

Solution 3 - Python

Try to replace args with kwargs={x: 1, y: 2}.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxennygrimmatoView Question on Stackoverflow
Solution 1 - PythonvladosaurusView Answer on Stackoverflow
Solution 2 - PythonDanielView Answer on Stackoverflow
Solution 3 - Pythonf43d65View Answer on Stackoverflow