ARGS vs KWARGS in Python

Imgur

Function Parameters: Python allows us to create functions to reuse our code. A function can also take in input values passed as arguments called parameters to run their code. More on Functions

Multiple Parameters: Functions can function without any argument, a single argument or multiple arguments at the same time depending upon the code they are executing.

But what if,

  • You are doubtful of the number of arguments your function needs? - What if your function needs a variable number of arguments?
  • Can you go back to changing your function code everytime or create different functions running the same code for different number of parameters?
This is where *args and **kwargs come into picture.

*args and **kwargs are special syntax's used while defining a function to pass a variable number of arguments. We will look at how to use them in the code examples below.

Remember: It is not complusory to use args and kwargs as parameter name, you can simply add the asterisk's but it is common practise to them so we will be sticking with that today.

*args

Args is used when we want to provide a variable number of arguments without passing any names/keywords. In this case we don't need to add and variable names for the arguments we are passing.

Args can be provided by adding a single star or asterisk (*).

Let's look at an example:

Imgur source

Say hypothetically we are designing our own sneakers. Below is a simple function to help us process a shoe of our choice of color.

def shoe_colors(*args):
  print("Processing {} sneaker.".format(args))

shoe_colors('blue', 'white', 'red', 'black', 'off-white')
Processing ('blue', 'white', 'red', 'black', 'off-white') sneaker.

In the function above, *args allows us to pass more than one argument when calling a function. The arguments we passed form a tuple which we can confirm by printing the type of args.

def shoe_colors(*args):
  print("Processing {} sneaker.".format(args))
  print("Argument Type", type(args))

shoe_colors('blue', 'white', 'red', 'black', 'off-white')
Processing ('blue', 'white', 'red', 'black', 'off-white') sneaker. Argument Type <class 'tuple'>

Now we managed to process a pair of sneakers with the colors above OR because its a hypothetical situation, a variety of different pairs with our chosen choice of colors.

But we should consider that, there are several components to a sneaker. Perhaps now, we need to mention keywords in our parameters so our function can give us the exact pair of sneakers we are looking for.

Here's where we will be needing arguments that are component specific. For this we will use **kwargs.

**kwargs

Kwargs is also used to add a variable number of arguments like *args but in this case the arguments are key-worded. Meaning, we have to pass the arguments along with their variable names.

Kwargs can be provided with two "**" asterisk signs before the parameter name.

Now, let's use this to customize our shoes into our perfect sneaker by providing more precise details.

def customize_shoe(**kwargs):
  print("Processing sneakers with ",kwargs)

customize_shoe(Vamp='Lt Madder', Collar='Psychic', Laces='White', Midsole='Sail')
Processing sneakers with {'Vamp': 'Lt Madder', 'Collar': 'Psychic', 'Laces': 'White', 'Midsole': 'Sail'}

In the example above, we were able to pass seperate variable names for different components without explicitly stating them suring the function definition. This time the arguments we pass form a dictionary and once again we can confirm this by the following code:

def customize_shoe(**kwargs):
  print("Processing sneakers with ",kwargs)
  print("Argument Type", type(kwargs))

customize_shoe(Vamp='Lt Madder', Collar='Psychic', Laces='White', Midsole='Sail')

Conclusion

Note that the above examples were only taken to make the concept of args and kwargs easier to grasp. The only difference between the two is that args allow us to take a variable number of positional arguments, whereas kwargs allow us to take a variable number of keyword arguments. As we saw above, both have very different use cases.

Difference between positional and keyword arguments.

!pip install jovian --upgrade --quiet
|████████████████████████████████| 68 kB 4.3 MB/s eta 0:00:011 Building wheel for uuid (setup.py) ... done
import jovian
# Execute this to save new versions of the notebook
jovian.commit(project="args-kwargs-python")
[jovian] Detected Colab notebook...
[jovian] Error: jovian.commit doesn't work on Colab unless the notebook was created and executed from Jovian. Make sure to run the first code cell at the top after executing from Jovian. Alternatively, you can download this notebook and upload it manually to Jovian. Learn more: https://jovian.ai/docs/user-guide/run.html#run-on-colab
himani007
Himani Gulati2 months ago
Jovian
Sign In