92

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.

2
  • 2
    Have you read the documentation? Commented Jun 18, 2015 at 10:48
  • 2
    You don't need to use specify the names of the arguments, you can use a plain tuple: t = threading.Thread(target=f, args=(1,2,)) Commented May 12, 2017 at 15:42

3 Answers 3

152
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'})
Sign up to request clarification or add additional context in comments.

2 Comments

Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.
I have no problem with vladosaurus's answer as it is. Longer isn't always more helpful; being concise is. In this case it saves my day within seconds.
16

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

Comments

1

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

2 Comments

Surely not. ITYM {'x': 1, 'y': 2}, which is a huge difference.
@ LoganSonOfGrim: Please do not add commentary to content that you edit explaining your edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.