*
vs **
They allow for functions to be defined to accept and for users to pass any number of arguments, positional (*
) and keyword (**
).
*args
vs **kwargs
when defining functions
*args
allows for any number of optional positional arguments (parameters), which will be assigned to a tuple named args
.**kwargs
allows for any number of optional keyword arguments (parameters), which will be in a dict named kwargs
.
Positional Arguments
1 | def test(a,b,c): |
This is a function definition with positional arguments. You can call it with keyword/named arguments as well:
1 | def test(a,b,c): |
Keyword Arguments
1 | def test(a=0,b=0,c=0): |
Can call this function with positional arguments as well:
1 | def test(a=0,b=0,c=0): |
*
vs **
These operators can be used in 2 areas:
a) function call
b) function definition
The use of *
operator and **
operator in function call
1 | def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2) |
Conclusion: when the *
or **
operator is used in a function call
*
operator unpacks data structure such as a list or tuple into arguments needed by function definition.
**
operator unpacks a dictionary into arguments needed by function definition.
The use of *
operator in function definition
1 | def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4)) |
In function definition the *
operator packs the received arguments into a tuple.
The use of **
operator in function definition
1 | def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4}) |
In function definition The **
operator packs the received arguments into a dictionary.
Therefore:
In a function call the *
unpacks data structure of tuple or list into positional or keyword arguments to be received by function definition.
In a function call the **
unpacks data structure of dictionary into positional or keyword arguments to be received by function definition.
In a function definition the *
packs positional arguments into a tuple.
In a function definition the **
packs keyword arguments into a dictionary.