Python kwargs and args

#Day16 – Positional Arguments, Keyword Arguments and the terms “args” and “kwargs”

Posted by

Positional Arguments and Keyword Arguments

  • When we call a function and DO NOT pass the parameter names along with the values, they are known as Positional Arguments.
  • When we call a function and DO pass the parameter names along with the values, they are known as Keyword Arguments
image.png

Args and Kwargs

If you have worked with Python, you might have come across a function like this

def func(*args, **kwargs):
    pass

The function func has a couple of parameters *args and **kwargs. The words args and kwargs are just naming conventions, what’s important are the “*” and “**” operators. They are also known as the unpacking operators.

Args

image.png

args stands for arguments. If the parameter of a function is *args, it can take in any number of Positional Arguments. args is basically like a tuple and we can iterate over it using the in operator. Since it is a tuple, it is immutable.

image.png

As mentioned above, “args” is just a naming convention. We can use “nums” or anything else.

Kwargs

**kwargs is similar to *args. The only difference is that it accepts multiple keyword arguments. Hence the name “kwargs”.

image.png

kwargs is like a dictionary. “kwargs” is also a naming convention and can be named anything.

image.png

Order of parameters

First, you should have the normal parameters followed by “*args” followed by “**kwargs”

image.png
  • 1 and 2 are assigned to num1 and num2 respectively
  • The rest of the positional arguments (3,4,5,6) are assigned to *args
  • parameter1 and parameter2 are assigned to **kwargs

Note on the order of Parameters

This doesn’t have anything to do with “args” or “kwargs”. The rule has to be followed when dealing with any function in Python.

In Python, you can not pass in Positional arguments after you pass in Keyword Arguments.

# Error
func(num1 = 1,num2 = 2,3,4,5,6,parameter1 = 10, parameter2 = 20 )

You will get the following error if you do so

SyntaxError: positional argument follows keyword argument

In the above function call, we pass in num1 and num2 as keyword arguments but then pass (3,4,5,6) as positional arguments. This is not allowed in Python and will result in the syntax error mentioned above.

However, we can pass in Keyword Arguments after Positional Arguments

# Correct
func(1,2,3,4,5,6,parameter1 = 10, parameter2 = 20 )

The above code snippet would be correct since there are no positional arguments after the keyword arguments

One comment

Comments are closed.