type(3,)
returns the int type, while
t = 3,
type(t)
returns the tuple type. Why?
Inside the parentheses that form the function call operator, the comma is not for building tuples, but for separating arguments. Thus, type(3, )
is equivalent to type(3)
. An additional comma at the end of the argument list is allowed by the grammar. You need an extra pair of parens to build a tuple:
>>> def f(x):
... print x
...
>>> f(3)
3
>>> f(3,)
3
>>> f((3,))
(3,)
The builtin type()
is a function, so the comma is being parsed as an argument separator rather than a tuple constructor.
>>> type(3,)
<type 'int'>
>>> type((3,))
<type 'tuple'>
I suspect Python ignores a trailing comma in function arguments:
def f (a):
print a
print type(a)
>>> f(3,)
3
<type 'int'>
Using comma-separated values without parentheses to create a tuple is a trick that doesn't work everywhere. List comprehensions is a good example:
>>> [a,a*2 for a in range(4)]
File "<stdin>", line 1
[a,a*2 for a in range(4)]
^
You have to do this:
>>> [(a,a*2) for a in range(4)]
[(0, 0), (1, 2), (2, 4), (3, 6)]
List unpacking works fine, though, so it's a bit variable where unbounded, comma-separated values are allowed:
>>> [(a,b) for a, b in zip(range(4),range(4))]
[(0, 0), (1, 1), (2, 2), (3, 3)]
In func(bunch_of_args)
you are allowed to follow the last arg with a comma, just like in
alist = [1, 2, 3, ]
f
takes, the comma will be parsed as an argument separator - Aaron Dufour 2012-04-03 21:43