9

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?

2
  • self.__target(*self.__args, **self.__kwargs) should probably be self.__target(self.__args, self.__kwargs). Otherwise you are passing every item in the dictionary as an argument.
    – Jonathan
    Commented Mar 20, 2014 at 19:13
  • The self.__target call is coming from the source for the threading module, definitely not where the problem is! Commented Mar 20, 2014 at 19:15

1 Answer 1

28

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.