What do * and ** before a variable name mean in a function signature?

Python

Python Problem Overview


> Possible Duplicate:
> Understanding kwargs in Python

I have read a piece of python code, and I don't know what does * and ** mean in this code :

def functionA(self, *a, **kw):
   // code here

I just know about one use of *: extract all attribute it has to parameter of method or constructor.

If this true for above function, so what does the rest : ** ?

Python Solutions


Solution 1 - Python

Inside a function header:

* collects all the positional arguments in a tuple.

** collects all the keyword arguments in a dictionary.

>>> def functionA(*a, **kw):
	   print(a)
	   print(kw)

	
>>> functionA(1, 2, 3, 4, 5, 6, a=2, b=3, c=5)
(1, 2, 3, 4, 5, 6)
{'a': 2, 'c': 5, 'b': 3}

In a function call:

* unpacks a list or tuple into position arguments.

** unpacks a dictionary into keyword arguments.

>>> lis=[1, 2, 3, 4]
>>> dic={'a': 10, 'b':20}
>>> functionA(*lis, **dic)  #it is similar to functionA(1, 2, 3, 4, a=10, b=20)
(1, 2, 3, 4)
{'a': 10, 'b': 20}

Solution 2 - Python

** takes specified argument names and puts them into a dictionary. So:

def func(**stuff):
    print(stuff)

func(one = 1, two = 2)

Would print:

{'one': 1, 'two': 2}

Solution 3 - Python

** means named arguments of the functions.

$ cat 2.py
def k(**argv):
    print argv

k(a=10, b = 20)

$ python 2.py
{'a': 10, 'b': 20}

argv is a dictionary that contains all named arguments of the function.

And you can also reverse it. You can use a dictionary as a set of aruments for a function:

def k(a=10, b=20):
  print a
  print b

d={'a':30,'b':40}
k(**d)

would print

30
40

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhqtView Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonRy-View Answer on Stackoverflow
Solution 3 - PythonIgor ChubinView Answer on Stackoverflow