Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference call function with asterisk parameter and without

I know what the meaning of an asterisk is in a function definition in Python.

I often, though, see asterisks for calls to functions with parameters like:

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

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

like image 223
Robert Moon Avatar asked Jul 03 '15 02:07

Robert Moon


People also ask

Can you call a function without a parameter?

You can use a default argument in Python if you wish to call your function without passing parameters. The function parameter takes the default value if the parameter is not supplied during the function call.

What happens when we prefix a parameter with an asterisk *?

The asterisk (star) operator is used in Python with more than one meaning attached to it. Single asterisk as used in function declaration allows variable number of arguments passed from calling environment.

What is asterisk in Python function parameter?

In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk ( * ) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.

What is * in function argument Python?

There are two ways to pass variable-length arguments to a python function. The first method is by using the single-asterisk (*) symbol. The single-asterisk is used to pass a variable number of non-keyworded arguments to the function.


1 Answers

Let args = [1,2,3]:

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

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

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

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

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

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

like image 197
LittleQ Avatar answered Sep 19 '22 12:09

LittleQ