Python: What do double parenthesis do?

BrianFreud picture BrianFreud · Apr 20, 2012 · Viewed 9.3k times · Source

Can anyone tell me why the parenthesis are doubled here?

self.__items.append((module, item))

Answer

senderle picture senderle · Apr 20, 2012

The inner parenthesis create a tuple.

>>> type(('a', 'b'))
<type 'tuple'>

Technically, tuples can be created without parenthesis:

>>> 'a', 'b'
('a', 'b')

But sometimes they need parenthesis:

>>> 'a', 'b' + 'c', 'd'
('a', 'bc', 'd')
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')

In your case, they need parenthesis to distinguish the tuple from the comma-separated arguments to a function. For example:

>>> def takes_one_arg(x):
...     return x
... 
>>> takes_one_arg('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: takes_one_arg() takes exactly 1 argument (2 given)
>>> takes_one_arg(('a', 'b'))
('a', 'b')