Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What do double parenthesis do?

Can anyone tell me why the parenthesis are doubled here?

self.__items.append((module, item))
like image 926
BrianFreud Avatar asked Apr 19 '12 22:04

BrianFreud


3 Answers

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')
like image 163
senderle Avatar answered Sep 20 '22 18:09

senderle


It's passing the tuple (module, item) to the function as a single argument. Without the extra parens, it would pass module and item as separate arguments.

like image 40
dan04 Avatar answered Sep 21 '22 18:09

dan04


That's exactly the same as saying:

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

I.e. the inner parens are first creating a tuple before the tuple is used as the single argument to append().

like image 20
sblom Avatar answered Sep 21 '22 18:09

sblom