Difference call function with and without asterisk

I know that the asterisk value is in the function definition in Python.

I often, however, see asterisks for function calls with parameters such as:

def foo(*args, **kwargs): first_func(args, kwargs) second_func(*args, **kwargs) 

What is the difference between the first and second function calls?

+12
python function-parameter argument-unpacking
source share
3 answers

Let args = [1,2,3] :

func(*args) == func(1,2,3) - variables are unpacked from the list (or any other type of sequence) as parameters

func(args) == func([1,2,3]) - list passed

Let kwargs = dict(a=1,b=2,c=3) :

func(kwargs) == func({'a':1, 'b':2, 'c':3}) - dictate passed

func(*kwargs) == func(('a','b','c')) - a tuple of dict keys (in random order)

func(**kwargs) == func(a=1,b=2,c=3) - (key, value) are unpacked from dict (or any other type of display) as named parameters

+20
source share

The difference is how the arguments are passed to the called functions. When you use * , the arguments are unpacked (if they are a list or a tuple); otherwise, they are simply transmitted as is.

Here is an example of the difference:

 >>> def add(a, b): ... print a + b ... >>> add(*[2,3]) 5 >>> add([2,3]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: add() takes exactly 2 arguments (1 given) >>> add(4, 5) 9 

When I prefix the argument * , it actually unpacked the list into two separate arguments, which were passed to add as a and b . Without it, it is simply passed in the list as one argument.

The same applies to dictionaries and ** , except that they are passed as names, not ordered arguments.

 >>> def show_two_stars(first, second='second', third='third'): ... print "first: " + str(first) ... print "second: " + str(second) ... print "third: " + str(third) >>> show_two_stars('a', 'b', 'c') first: a second: b third: c >>> show_two_stars(**{'second': 'hey', 'first': 'you'}) first: you second: hey third: third >>> show_two_stars({'second': 'hey', 'first': 'you'}) first: {'second': 'hey', 'first': 'you'} second: second third: third 
+9
source share
 def fun1(*args): """ This function accepts a non keyworded variable length argument as a parameter. """ print args print len(args) >>> a = [] >>> fun1(a) ([],) 1 # This clearly shows that, the empty list itself is passed as a first argument. Since *args now contains one empty list as its first argument, so the length is 1 >>> fun1(*a) () 0 # Here the empty list is unwrapped (elements are brought out as separate variable length arguments) and passed to the function. Since there is no element inside, the length of *args is 0 >>> 
0
source share

All Articles