Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 805
hqt Avatar asked Jul 03 '12 16:07

hqt


People also ask

What does * mean in Python function?

The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.

What does * Before list mean in Python?

Here single asterisk( * ) is also used in *args. It is used to pass a variable number of arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list.

What is the signature of a function in Python?

Python callables have a signature: the interface which describes what arguments are accepted and (optionally) what kind of value is returned. The function func (above) has the signature (a, b, c) . We know that it requires three arguments, one for a , b and c . These ( a , b and c ) are called parameters.


2 Answers

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} 
like image 176
Ashwini Chaudhary Avatar answered Oct 02 '22 07:10

Ashwini Chaudhary


** 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} 
like image 44
Ry- Avatar answered Oct 02 '22 07:10

Ry-