Python *args and **kwargs
What are they actually?
Python is a powerful programming language that enables programmers to create clear and easy-to-maintain code. The ability to define functions with flexible arguments is one of the characteristics of Python that contributes to its versatility. I assume you know what python functions and arguments are. So, let's dive into *args and **kwargs, two of the most popular Python arguments.
args: The args (short for “arguments”) keyword specifies that a function can accept a variable number of non-keyword arguments. The syntax is straightforward; you simply indicate to Python that the function can accept any number of non-keyword arguments by prefixing the parameter name with an asterisk ‘ * ’. We can use *args to accept any number of numbers, for example, if we want to write a function that computes the average of a list of numbers.
def avg(*numbers):
total = 0
for number in numbers:
total += number
return total/len(numbers)
print(avg(1, 2, 3, 4, 5)) # 3.0
print(avg(2, 2, 4, 6)) # 3.5In this case, the function “avg” computes the average of the numbers and accepts any number of non-keyword arguments. The *args syntax informs Python that this function can accept any number of non-keyword arguments, and those arguments will be passed to the function as a tuple. After that, the tuple is unpacked, and its elements are accessed individually. ‘numbers’ The name “numbers” for the parameter is merely a convention; you can name it anything. For example, you can name them “digits” or “my_favorite_numbers” or any other name you like.
Get Dipesh Basnet’s stories in your inbox
Join Medium for free to get updates from this writer.
kwargs: Similar to *args, **kwargs (short for “keyword arguments”) allows a function to accept a variable number of keyword arguments. The function receives these keyword arguments as a dictionary. You must add two asterisks before the parameter name in order to use kwargs in a function ‘ ** ’. For instance, if we wanted to create a function that prints a user’s details, we could use **kwargs, which could take any number of keyword arguments.
def user_details(**user_info):
for key, value in user_info.items():
print(key, ":", value)
user_details(name="Dipesh Basnet", age=25, course="Computer Science")
# Output:
# name : Dipesh Basnet
# age : 25
# course : Computer ScienceIn this example, the function “user_details” accepts any number of keyword parameters and outputs both the key and value of each. The **kwargs syntax instructs Python that this function can take as many keyword arguments as it likes, and that they will be supplied to it as a dictionary that can be accessed as key-value pairs. The name “user_info” for the parameter is merely a convention, similar to that of *args, and it might be given any name. For instance, you can name it “user_description” or “details_of_user”, or anything you like. Just make sure the name is clear and does not cause any confusion later on.
Both *args and **kwargs may be used in the same function, which is totally possible. For example, suppose we want to create a function that computes the average score and prints a user’s score and details.
def user_details(*score, **info):
average_score = sum(score)/len(score) # using inbuilt sum() function
for key, value in info.items():
print(key, ":", value)
print("average score:", round(average_score, 2)) # round() function for rounding up the result decimal
user_details(3, 2, 3, name="Dipesh Basnet", age=25, course="MSCS", semester="First")
# Output:
# name : Dipesh Basnet
# age : 2
# course : MSCS
# semester : First
# average score: 2.67In this example, the function “user_details” calculates the average of the scores which are (3, 2, and 3) and prints the user’s details after accepting any number of keyword and non-keyword arguments. As a result, the function is incredibly flexible and reusable.
In conclusion, Python’s *args and **kwargs features are fantastic tools that let programmers design functions that can accept a configurable number of argument types as well as keyword arguments. Functions become more adaptable and reusable as a result. Additionally, it’s a useful tool to have if you’re a Python developer. With the help of these examples, you ought to be able to understand how to use *args and **kwargs in your functions in order to increase their adaptability and reuse.






