If you are new Python and saw the use of *args and **kwargs as function arguments and wondered what those *-thingies are, you are not alone.
Typically when you write functions, you will have specific number and types of arguments the function can take as input. However, the more Python code you write, you might end up with scenarios, where you might have to write functions that can take un-specified number of arguments.
That is where *args and *kwargs come to rescue you. Basically, *args kind of means any number of arguments and **kwargs – means any number of arguments with keywords.
*args Usage
Let us quickly see how it works and how we can use it with a simple example. Let us define a new function that takes *args as arguments.
# function showing the usage of *args >def args_example(*args): print(args)
Our args_example function is a simple one. The function just prints its arguments. Let us try with simple example. First, we gave just one argument and it printed that argument as tuple. Next, we gave 5 arguments and it just printed as a tuple. The values of *args inside a function are tuples.
>args_example(1) (1,) >args_example(1,2,3,4,5) (1, 2, 3, 4, 5)
Let us use another simple function to illustrate what **kwargs does.
**kwargs Usage
**kwargs allows you to write functions with arbitrary number of arguments with names (or keywords) associated with it. The number of arguments is variable, because you don’t know ahead how many arguments will the function get. Let us see a simple function using **kwargs.
# function showing the usage of **kwargs >def kwargs_example(**kwargs): for key, value in kwargs.items(): # printing the key and value pairs print(key + ': ' + value)
Inside a function the variable keyword arguments are available as a dictionary, where the name or keywords of the argument are keys and the values of the argument are values in the dictionary. Let us see how **kwargs works.
>kwargs_example(one='1') one: 1 >print('kwargs example 2') >kwargs_example(one='1',two='2',three='3',four='4') one: 1 two: 2 three: 3 four: 4
In the first use case for **kwargs, the function got just one argument with a keyword and in the second use case the kwargs_example function got 4 arguments with keywords. The function could handle the variable number of arguments easily as inside the function the keyword and the arguments are stored as a dictionary.