78

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.

xennygrimmato
  • 2,646
  • 7
  • 25
  • 47
  • 2
    Have you read [the documentation](https://docs.python.org/2/library/threading.html#threading.Thread)? – jonrsharpe Jun 18 '15 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,))` – bonh May 12 '17 at 15:42

3 Answers3

133
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'})
vladosaurus
  • 1,638
  • 1
  • 13
  • 18
  • 3
    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. – SuperBiasedMan Sep 22 '15 at 13:47
  • 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. – Jerry Hu Jan 12 '18 at 04:31
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()
Daniel
  • 3,344
  • 5
  • 27
  • 35
0

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

f43d65
  • 2,264
  • 11
  • 15