1

This is a very basic doubt that came to my mind. When we use threading module in python to start a new thread, I have see two different ways in which arguments are passed to with the call:

Version 1:

thread = threading.Thread(target=tar,args=(4,0.25,))

Version 2:

thread = threading.Thread(target=tar,args=(4,0.25))

The difference is the addition of , at the end of argument list at the end of version 1 call. Both the versions work fine but I want to know if theres any significant difference between the two versions above and if than which ones a better way to write? If theres no difference than what is the reason a lot of people and articles choose to use version 1 and add a redundant , at the end of the argument list.

Matthew Nizol
  • 2,609
  • 1
  • 18
  • 22
Jason Donnald
  • 2,256
  • 9
  • 36
  • 49
  • 6
    No, frequently you will see something like args=(4,) but rarely do people say args=(4, 0.25,). The reason for the trailing comma is to flag to the compiler that the value being read is a tuple. (4) just parses as 4, but (4,) is the tuple containing 4 as its only element. (4, 0.25) is already a tuple. – Darren Ringer Apr 24 '15 at 21:52
  • 3
    It not only applies to tuples, but lists and dicts. http://stackoverflow.com/questions/11597901/why-does-python-allow-a-trailing-comma-in-list for a reason – C.B. Apr 24 '15 at 21:56
  • My thoughts on it not being idiomatic to see a trailing comma in a tuple declaration weren't *exactly* correct...I'd love to see an explanation that justifies the difference. My stance remains: I don't believe that there's a difference between the two function-wise. – Makoto Apr 24 '15 at 21:57
  • @DarrenRinger so if I understand correct when you pass just one argument than you need a trailing comma so as to tell compiler that its a tuple but if you have more than 1 argument than you don't need trailing comma right? – Jason Donnald Apr 25 '15 at 01:08

1 Answers1

2

The two forms of writing a 2-tuple are equivalent. Proof:

>>> (4,0.25,) == (4,0.25)
True

For an elaboration on valid tuple syntax in Python, see https://wiki.python.org/moin/TupleSyntax. Specifically:

In Python, multiple-element tuples look like:

1,2,3

The essential elements are the commas between each element of the tuple. Multiple-element tuples may be written with a trailing comma, e.g.

1,2,3,

but the trailing comma is completely optional.

Matthew Nizol
  • 2,609
  • 1
  • 18
  • 22