Monday, October 2, 2017

Understanding Args and Kwargs in Python

Understanding Args and Kwargs in Python

In this tutorial, I will be focusing on arguments (*args) and keyword arguments (*kwargs) in Python.

I will teach you what args and kwargs are and, most importantly, how to use them—that is how to take in an unlimited number of arguments and keyword arguments in functions.

What Are Args?

*args are used to pass non-keyword arguments. Examples of non-keyword arguments are fun(3,4), fun("foo","bar").

*args are usually used as a measure to prevent the program from crashing if we don’t know how many arguments will be passed to the function. This is used in C++ as well as other programming languages.

What Are Kwargs?

**kwargs is a dictionary of keyword arguments. The ** allows us to pass any number of keyword arguments. A keyword argument is basically a dictionary.

An example of a keyword argument is fun(foo=2,bar=7).

**kwargs are just like *args except you declare the variables and the amount within the function arguments.

Where to Use Args and Kwargs

Args and kwargs are useful when you want to:

  • Reduce code rewriting.
  • Make your code readable.
  • Reuse your code

Using Args and Kwargs in Functions

Let's look at how kwargs and args are used in functions.

Args

The function below takes in three arguments. The three arguments have been explicitly defined, so any more or less will cause an error in the program.

Let's run the function. The function will add the three numbers, giving the following output:

What if we were to pass four arguments in the function instead of the required three? We will receive an error as shown below.

This is because only three parameters were defined in the function, but we have passed four positional arguments when calling the function.

In the second example below, the * is for non-keyword arguments and gets passed into the function. Instead of having defined arguments, we replace a, b and c with a single parameter (*args).

Notice how the use of *args makes it easy to use any number of arguments without having to change your code. *args provide more flexibility to your code since you can have as many arguments as you wish in the future.

More Examples

Create a simple function as shown:

Test the function using a combination of integers and strings:

What if we were to pass a list as an argument? Test the function with a list by replacing the previous arguments with a list,  l = [11,3,4,5,"tuts].

From the above example, you can also use *args to unpack arguments that are already in a list or a tuple so that all elements in the list are passed as different parameters.

Using the same function:

 

Kwargs

Kwargs allow you to pass keyword arguments to a function. They are used when you are not sure of the number of keyword arguments that will be passed in the function.

Write a function my_func and pass in (x= 10, y =20) as keyword arguments as shown below:

Kwargs can be used for unpacking dictionary key, value pairs. This is done using the double asterisk notation (**). It's important to note that each key must be matched with a value.

Here's a typical example of how it's done. The function below takes countries as keys and their capital cities as the values. It then prints out a statement which iterates over the kwargs and maps each keyword to the value assigned to it.

You can call the function with any arguments you want.

For a more complex example, suppose we have a model for a customer that looks something like this:

You can use kwargs to do both data inputs and data queries from model objects. Let's write a function view in order to create a new customer.

Here is how to perform a query of the customer we just created using kwargs.

Using Both Args and Kwargs in a Function

When using both args and kwargs in the same function definition, *args must occur before **kwargs

Example:

Remember args should come before kwargs.

Conclusion

I hope this tutorial has helped you understand args and kwargs.

Below are some pointers to remember when using args and kwargs:

  • *args and **kwargs are special syntax that are used in functions to pass a variable number of arguments to a function.
  • *args occur before **kwargs in a function definition.
  • *args and **kwargs are best used in situations where the number of inputs will remain relatively small.
  • You can use any name you want; args and kwargs are only by convention and not a requirement. For example, you can use *foo instead of *args or **foo instead of **kwargs.

The official Python documentation offers a lot of information for further study. Additionally, don’t hesitate to see what we have available for sale and for study in the marketplace, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.


No comments:

Post a Comment