1

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Drake P
  • 174
  • 9
  • `(anything) === anything`, however `[anything]` is always a list ... if you add a trailing comma than `(anything,)` becomes a tuple with the first thing as the thing – Joran Beasley Jul 17 '21 at 00:53
  • @JoranBeasley I don't comprehend what you're trying to communicate. Perhaps you could expound on your thoughts in an answer? – Drake P Jul 17 '21 at 01:01

1 Answers1

2

Because the comma makes the tuple, or so the saying goes.

(1) is just grouping parens, but (1, ) is a tuple with one int. In this case under the hood the thread initializer is unpacking args, so without the comma it's unpacking test list, basically test_func(*test_list) but with the comma it unpacks the tuple, and everything works.

dcbaker
  • 643
  • 2
  • 7
  • Ahh I see, the unpacking args explanation was what I wasn't understanding (and wasn't gleaning from other questions). Thank you for the help! – Drake P Jul 17 '21 at 03:52