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

Posted on

Question :

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

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 : ** ?

Asked By: hqt

||

Answer #1:

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}
Answered By: Ashwini Chaudhary

Answer #2:

** 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}
Answered By: Ry-

Answer #3:

** 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
Answered By: Igor Chubin

Leave a Reply

Your email address will not be published.