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

Question:

What do the * and ** mean in this code?

def functionA(self, *a, **kw):
   # code here
Asked By: hqt

||

Answers:

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

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

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
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.