drhanlau
drhanlau

Reputation: 2527

Python tuple question

I am reading this

http://docs.python.org/dev/library/multiprocessing.html

In particular this

p = multiprocessing.Process(target=time.sleep, args=(1000,))

I tried the same thing, but if I remove the "," after 1000 it doesn't work. So my question is what is the semantic behind the args=(1000,) in this case? What is the difference if I put a comma and not ?

p/s: I believe it's a fundamental issue, if it is can someone point me to some further reading if possible? thanks.

Thanks.

Regards, Andy.

Upvotes: 1

Views: 312

Answers (4)

Chris Cooper
Chris Cooper

Reputation: 17594

If you just put (1000), Python assumes you're just evaluating the expression as math, hence it gets simplified to just 1000. Think of the result of 5 + (1000) + 4.

Just as the expression above would get simplified to 1009, here is what your line looks like once things have been simplified:

p = multiprocessing.Process(target=time.sleep, args=1000)

You can see that this is not the same thing at all. args is supposed to be a tuple of arguments, not a single integer.

If you put (1000,), Python can tell you are looking for a tuple which only contains one element, since that expression is differentiable from a simple arithmetic expression, so you end up passing in the correct thing.

Upvotes: 11

Rafe Kettler
Rafe Kettler

Reputation: 76985

It's a one-tuple. It's a syntax wart in Python, but think about it: how could you tell that (500) is a tuple and not just 500? Since parentheses are also used for order of operations in Python, you need some differentiation. You have to have the trailing comma if you're only going to have one element in the tuple.

Upvotes: 2

senderle
senderle

Reputation: 151187

It's very simple -- the python interpreter has to be able to tell the difference between putting a value in parentheses -- (1000) -- and putting it into a tuple: (1000,).

Upvotes: 2

Pwnna
Pwnna

Reputation: 9538

(1000) to the interpreter simply means that it's 1000 in a set of brackets. It has identical meanings to (1000+1000), and as you can see, that's not a tuple, either.

Upvotes: 0

Related Questions