Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do we have to add comma ',' in args in python multithreading?

I am new to python and I am not sure why we use Comma ‘,’ in args for Thread
Eg:

import threading
import time

semaphore = threading.BoundedSemaphore(value=5)

def access(thread_number):
    print("{}: Trying access...".format(thread_number))

    semaphore.acquire()

    print("{}: Access granted!".format(thread_number))

    print("{}: waiting 5 seconds...".format(thread_number))

    time.sleep(5)
    semaphore.release()

    print("{}: Releasing!...".format(thread_number))


for thread_number in range(10):
    t = threading.Thread(target=access, args=(thread_number,))
    t.start()

Why is it valid?
how does "args = (thread_number,)" need comma at the end?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Alas, this isn’t especially easy – it’s at the intersection of some dark corners of Python’s syntax.

First, the comma is needed to make a tuple, with a single element, containing the thread number:

>>> 6
6
>>> 6,
(6,)
>>> (6,)
(6,)
>>> (6)
6

See? Without a comma, or with just parentheses, 6 is just the int 6. But with a comma – and with or without parentheses – it becomes a tuple containing the int 6 as its only element.

Why does it need to be a tuple? You’re soon going to be told that it actually doesn’t 😉 , but before then consider that you may need to pass any number of arguments to a thread. So the expression after args= must yield a sequence.

But if the appearance of comma makes a tuple, why do you also need parentheses? That’s an "intersection of some dark corners": a comma in an argument list also seperates arguments, and that takes precedence in this context. So the parentheses are needed to enforce the intent: "this comma doesn’t mean the next argument is starting – this comma means I want a tuple".

To avoid having to think about all that, you can use a list as a sequence instead in this context:

    t = threading.Thread(target=access, args=[thread_number])

The implementation of Thread couldn’t care less which kind of sequence is passed as the value of args=, and lots of code actually uses a list instead of a tuple. However, last time I looked, that had not been documented, so it’s a bit risky.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading