I was attempting to use the threading
package in Python 3 and ran into a situation about trailing commas I don't understand.
Here is the code, without a comma:
import threading
def thread_func(my_list):
print(my_list)
if __name__ == '__main__':
test_list = [ 1, 2, 3 ]
my_thread = threading.Thread(target=thread_func, args=(test_list)) # WITHOUT comma
my_thread.start()
which gives this error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
TypeError: thread_func() takes 1 positional argument but 3 were given
As you can see, Python tried to "unravel" the list and pass it as if each element were an argument.
If I add a comma to the args value, it works correctly:
import threading
def thread_func(my_list):
print(my_list)
if __name__ == '__main__':
test_list = [ 1, 2, 3 ]
my_thread = threading.Thread(target=thread_func, args=(test_list,)) # WITH comma
my_thread.start()
Output:
[1, 2, 3]
Normally, if I wanted to pass a list as an argument to this function, I would use the structure thread_func(test_list)
and it would work fine. Why is a trailing comma needed here?