How To Use *args and **kwargs In Python
Tags: python, django, programming, webdev
Published: 2023-08-10 12:47:12

## Introduction
Python, a programming language known for being simple and readable. One of the reason it is so popular is it way of handling parameters in function in a very easy and dynamic way with the use of *args and **kwargs. In this article, you will learn how to use these things to handle parameters in functions while writing your code.


## Understand Parameters In Function
In programming, a function is a block of code that can be reused and can be called multiple times. While parameters are the values you include in your function which make the function to perform some operations when you call it.

```python
def hello(greetings)
    return greetings

output = hello(Welcome)
print(output)
# It will print out: Welcome
```
In this case, hello is the function, greetings is the parameter.

### The Types of Parameters in a Function
1. Positional arguments
2. Keyword arguments

**Positional Arguments** are arguments that are passed in the order defined by the function.

```python
def hello(greetings, name)
    return greetings, name

output = hello(Welcome, Faith)
print(output)
# It will print out: Welcome, Faith
```


**Keyword Arguments** are identified by their parameter names.
```python
def hello(greetings='Welcome', name='Faith')
    return greetings, name

output = hello()
print(output)
# It will print out: Welcome, Faith
```

## Why Args and Kwargs is Used
Args and Kwargs are used when the number of arguments to be passed may vary or you don't know how many arguments a user may input into the function.

## *args
args mean *arguments*. When you use *args, the function can accept multiple numbers of values. The `*` (asterik) sign before the name to denote *args. When you pass *args as a parameter, it is treated as a tuple that contains all the positional arguments passed when you call the function. This feature is particularly useful when you're unsure about the number of arguments your function might receive.
Here is an example:
```python
def calculate_sum(*args):
    total = 0
    for num in args:
        total += num
    return total

result = calculate_sum(5, 10, 15, 20)
print(result)  # Output: 50
```

**Note:** You can use another name instead of args
For example
```python
def calculate_sum(*nums):
    total = 0
    for num in nums:
        total += num
    return total

result = calculate_sum(5, 10, 15, 20)
print(result)  # Output: 50
```
It will still give the same result.


## **Kwargs
**kwargs stands for "keyword arguments". Here we use double asterik `**` to identify keyword arguments. It allows a function to accept an arbitrary number of keyword arguments, that forms a dictionary inside the function. This dictionary-like structure allows you to access the values using their respective keys.

Here is an example:
```python
def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

display_info(name="Alice", age=30, profession="Engineer")
# Output:
# name: Alice
# age: 30
# profession: Engineer
```
**Note:** You can use another name instead of kwargs.
```python
def display_info(**data):
    for key, value in data.items():
        print(f"{key}: {value}")

display_info(name="Alice", age=30, profession="Engineer")
# Output:
# name: Alice
# age: 30
# profession: Engineer
```

## Combining *args and **kwargs
Now that you have understand args and kwargs, you are ready to use it in your code. What if you need to create functions that accept both a varying number of positional arguments and keyword arguments?

In this case, it can be achieved by using both *args and **kwargs in the same function. And you have to understand that it has to be in the right order.

Here is the correct order for your parameters:
`Standard arguments ---> *args ---> **kwargs`

Here is a representation of it.
```python
def combined_argument(a, b, *args, **kwargs):
    pass
```
**Not**
```python
def combined_argument(a, b, **kwargs, *args):
    pass
```
**OR**
```python
def combined_argument(*args, **kwargs, a, b):
    pass
```


## Best Practices and Tips:
* Use descriptive variable names to make your code readable.
* Document your functions properly, to indicate how *args and **kwargs are used in that function.
* Be cautious not to overcomplicate your function interfaces; use these features judiciously.
* When using *args and **kwargs together, maintain a clear order of arguments in the function signature.


## Conclusion:
Now you can go ahead, make use of *args and **kwargs, and level up function parameter handling in your projects.