Args and Kwargs in python


You’ve probably seen the parameters *args and **kwargs in function definitions or library documentation, but what exactly do they do?

When defining functions, you can specify one or more arguments as input. However, if you don’t know the exact number of inputs or want to add more inputs in the future, these two parameters come into play.

*args

If a function uses this parameter, it takes all the given inputs in sequence and puts them into the parameters. Any extra inputs beyond the fixed number are assigned to *args.

def example(one, *args):
    print(one)  # 'hello'
    print(args)  # (2, 3, 4)

example('hello', 2, 3, 4)

In this example, the function fills the one input with "hello" and puts the remaining inputs into *args. You can then iterate over the values in *args and use them in further commands.

*args is a set of position-based parameters, meaning the order of inputs matters, and you can access them in the function accordingly.

**kwargs

This parameter, like *args, is used for additional inputs to functions but in a dictionary format. The inputs given through this parameter must be defined as {key: value} pairs.

def example(arg1, **kwargs):
    print(arg1)  # 'Hi'
    print(kwargs)  # {'arg2': 'world', 'arg3': 123}

example(arg1='Hi', arg2='world', arg3=123)

In this example, the arg1 input is filled with "Hi" and the remaining inputs are assigned to **kwargs. Instead of slicing like in *args, you can access the desired value using the key.

Example usage of **kwargs in object initialization:

class car():
    # args receives unlimited no. of arguments as an array
    def __init__(self, **kwargs):
        # access args index like array does
        self.speed = kwargs['s']
        self.color = kwargs['c']
 
 
# creating objects of car class
audi = car(s=200, c='red')
bmw = car(s=250, c='black')
 
# printing the color and speed of cars
print(audi.color)
print(bmw.speed)

Combining *args and **kwargs:

In some cases, both parameters can be used together in a function definition.

def myFun(*args, **kwargs):
	print("args: ", args)
	print("kwargs: ", kwargs)


# Now we can use both *args ,**kwargs
# to pass arguments to this function :
myFun('THis', 'is', 'linkedin', first="article", mid="enjoy", last="it!")

Final Note:

The naming for these two parameters is flexible; any name that follows * or ** will have the same functionality as described above.

Further Reading:
https://realpython.com/python-kwargs-and-args/

Share

Leave a Reply

Your email address will not be published. Required fields are marked *