How to use Keyword Arguments in Python
Tags: python, programming, api
Published: 2023-05-22 06:17:07

## Introduction to Kwargs
In python, keyword arguments aka kwargs give developers the power create a function that can accept a variable number of arguments. Unlike the normal set up for a function where the argument amount is strictly defined, kwargs allow one to pass a dynamic set of key-value pairs in as arguments. This is extremely helpful for use-cases where your function may have optional or varying parameters. 

## Overview of Usage and Syntax 
To use kwargs, we need to add a special keyword parameter into the argument of the function, `**kwargs`. When this is set, it will give you the option to add any key-pair argument into the argument section when you call said function. Inside of your function using kwargs these values will be treated like a dictionary, allowing you to access them. Using standard dictionary operations like `kwargs['key']` or `kwargs.get('key')` you are able to retrieve the value giving to the function. It should be noted the word kwargs is not required but it is considered the best practice. Any variable name could be used in replace of it as long as you add `**` to the front of it in the argument section. 

## Examples of Usage

Lets say you have a function to print out characteristics of different types of pets. Now that gives us a wide range of inputs that we would need to accept to get all the information given. Using kwargs we are able to handle all of these inputs simply. 

```python
def print_pets(**kwargs):
    print(f"Name: {kwargs['name']}")
    print(f"Age: {kwargs['age']}")
    print(f"Type: {kwargs['type']}")

print_pets(name='Copper', age=12, type='golden retriever')
```
**Output:**
```
Name: Copper
Age: 12
Type: golden retriever
```

Now lets say we wanted to add another pet to this function but we don't know how old they are? With kwargs we don't need to include it in the arguments. In this case will will have to change the internal code as using the []'s to index the dictionary does not handle missing values even know kwargs does. Replacing these brackets with the get() function will fix this error though!

```python
def print_pets(**kwargs):
    print(f"Name: {kwargs.get('name')}")
    print(f"Age: {kwargs.get('age')}")
    print(f"Type: {kwargs.get('type')}")

print_pets(name='Betsy', type='poodle')
```
**Output:**
```
Name: Betsy
Age: None
Type: poodle
```

Also, it should be noted that you can still place explicit arguments into the function for functions that would be considered required. Using our previous example lets make the name of our pet required for the function while making the rest optional. 

```python
def print_pets(name, **kwargs):
    print(f"Name: {name}")
    print(f"Age: {kwargs['age']}")
    print(f"Type: {kwargs['type']}")

print_pets('Copper', age=12, type='golden retriever')
```
**Output:**
```
Name: Copper
Age: 12
Type: golden retriever
```

## Conclusion
Kwargs can offer a wide range of benefits when programming within Python. It allows for much more readable function calls that can dynamically change for the users needs. They offer a familiar way to handle the arguments of a function by internally placing them in a dictionary for use. They have several use-cases that would be a nightmare without this functionality. One in particular is when creating APIs and allowing the user to be able to customize their queries and responses based on their given arguments. This not only benefits the user but you as a developer as you are starting to make more readable and concise code!

Thank you for reading my article! If you learned something new or have an thoughts, please like and comment. Cheers :wave: