Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a dictionary to threaded function in Python

So, I have a function explain(item) that takes 1 argument. This argument is intended to be a dictionary with 8-9 keys. When I call explain(item) everything is fine. But when I call (items is the same variable)

threads.append(threading.Thread(target = explain, args=(item)))
threads[i].start()
threads[i].join()

I get errors like this one:

Exception in thread Thread-72:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: explain() takes exactly 1 argument (10 given)

What am I doing wrong?

like image 863
RomaValcer Avatar asked Mar 20 '14 19:03

RomaValcer


1 Answers

Looks like you are intending to pass a one-item tuple as the args parameter to threading.Thread() but using args=(item) is equivalent to args=item. You need to add a comma to create a tuple, so it would be args=(item,):

threads.append(threading.Thread(target = explain, args=(item,))).

Without the trailing comma the parentheses are just a method for grouping an expression, for example:

>>> (100)  # this is just the value 100
100
>>> (100,) # this is a one-element tuple that contains 100
(100,)
like image 83
Andrew Clark Avatar answered Oct 15 '22 12:10

Andrew Clark