Two stars in python "**", what do they do?

published Mar 18, 2010 02:10   by admin ( last modified Mar 25, 2016 11:30 )

Searching for "**" on Google does not give much.

The two stars prefix in python converts between dictionaries and named arguments.

>>> def twoargs(one=None,two=None):
...     return (two,one)

The above function takes two named arguments, "one" and "two".

However it can still be called as if the arguments were just positional:

>>> twoargs(32,3)
(3, 32)

And it can be called with named arguments:

>>> twoargs(two=32,one=3)
(32, 3)

But, what if we call it with a dictionary as a parameter?

>>> adict = {'one':3232,'two':886}
>>> twoargs(adict)
(None, {'two': 886, 'one': 3232})

The dictionary will be assigned positionally to the first argument ("one"). Since the function happens to return its arguments in reverse order, we first get None for the the last argument in, and then the dictionary.

However if we put two stars in front of the dictionary when calling the function, the dictionary is transformed into named arguments

>>> twoargs(**adict)
(886, 3232)

This showed a function with two named arguments, called with the two stars prefix. One can also do it the other way around, that is put the stars in the arguments in the function definition:

>>>
>>> def someargs(**args):
...     return args

The above function will take any number of named arguments, and put them into a dictionary called "args".

>>> someargs(one=323)
{'one': 323}

It doesn't like positional arguments:

>>> someargs(323)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: someargs() takes exactly 0 arguments (1 given)

For positional arguments one can use the single star prefix.

So, when the two stars are used calling a function:

  • They convert a dictionary into named arguments

 

When the two stars are used in the function definition:

  • They convert named arguments into a dictionary