What are python args and kwargs
In this tutorial we will learn what are python args and kwargs, this article assumes you have basic knowledge of python programming language, if you are a beginner you can get that basic knowledge here python tutorial.
we are going to start with python args , normally it is written like this *args
with a single asterick before args
. when you do not know the number of arguments that will be passed to the function you use the single asterick.
I am going to use an example to explain how python *args
works
def favorite_car(*cars):
print(cars)
print("My favorite car brand is " + cars[2])
favorite_car("Toyota", "Volkswagen", "Peugeot", "Chevrolet")
The output of the above code is :
('Toyota', 'Volkswagen', 'Peugeot', 'Chevrolet')
My favorite car brand is Peugeot
lets move now to **kwargs
(Keyword Arguments)
We use double asterick because it allows us to pass any number of keyword arguments
example:
def my_function(**kwargs):
print(kwargs)
my_function(name="John", age="28")
The output of the above code is
{'age': '28', 'name': 'John'}
I hope you have learned something from this post
Resources
Keep Learning
- How to pass user object to Django form
- What is super() in python
- What to do when Django's static files are not working