4

The following code does not print what I would expect:

#!/usr/bin/env python

print type(1,)
a = 1,
print type(a)

Here is the output:

<type 'int'>
<type 'tuple'>

I understand that the comma makes a into a tuple. But if that is the case how come the original print is not printing a tuple type but an int?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ivan Novick
  • 745
  • 2
  • 8
  • 12

3 Answers3

9

Because the tuple syntax inside a function call is also the way parameters are passed:

>>> print type(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments

>>> print type((1,))
<type 'tuple'>

>>> a = 1,
>>> type(a)
<type 'tuple'>

It is a syntax ambiguity for python, which it solves by deciding that you are trying to pass a parameter (if you ask me, it should be a syntax error though).

>>> print type(1,)
>>> print type(1)

Are the same.

fresskoma
  • 25,481
  • 10
  • 85
  • 128
  • While the point is definitely arguable, the reason it *isn't* a `SyntaxError` to include a trailing comma in an argument list is to maintain consistency between `(1,)` and `tuple(1,)` and `[1,]` and `list(1,)`. – ncoghlan May 15 '11 at 13:45
1

type() is a function, so the python parser will pass everything between the parenthesis of the type function call as the argument tuple to that function.

Thus, to pass a literal tuple to a function call you'll always need to add the parenthesis to the tuple for the parser to recognize it as such:

print type((1,))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Because it's not enclosed in parentheses: type((1,))

Without the extra parentheses it's treated as a simple parameter list in this context and the trailing semicolon is simply ignored.

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122