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.
def add(a, b,c): print(a+b+c) print add(2,3,4)
Let's run the function. The function will add the three numbers, giving the following output:
Output 9
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.
def add(a, b,c): print(a+b+c) print add(2,3,4,5)
Output TypeError: add() takes 3 positional arguments but 4 were given
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.
def add(*args): total = 0 for arg in args: total+=arg print total
Scenario 1 print add(1,2,5) Output 8
Scenario 2 print add(1,2,5,6) output 14
Scenario 3 print add(1,2,5,8) Output 16
More Examples
Create a simple function as shown:
def func(*args): # *args means for however many arguments you take in, it will catch them all for arg in args: print arg
Test the function using a combination of integers and strings:
def func(*args): # *args means for however many arguments you take in, it will catch them all for arg in args: print arg print func(11,3,4,5,"tuts")
Output 11 3 4 5 tuts
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]
.
def func(*args): # *args means for however many arguments you take in, it will catch them all for arg in args: print arg l = [11,3,4,5,"tuts"] print func(l)
This prints the list as a whole, This is because its interpreting the list as one item. Output [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:
def func(*args): # *args means for however many arguments you take in, it will catch them all for arg in args: print(arg) l = [11,3,4,5,"tuts"] print(func(*l))
The * will unpack the list and output each individual list item. Output 11 3 4 5 tuts
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:
def my_func(x=10,y=20): print x,y
This prints out the values of x and y Output 10,20
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.
def capital_cities(**kwargs): # initialize an empty list to store the result result = [] for key, value in kwargs.items(): result.append("The capital city of {} is {} .format (key,value) return result
You can call the function with any arguments you want.
def capital_cities(**kwargs): # initialize an empty list to store the result result = [] for key, value in kwargs.items(): result.append("The capital city of {} is {} .format (key,value) return result print capital_city(China = "Beijing",Cairo = "Egypt",Rome = "Italy"))
output ['The capital city of China is Beijing', 'The capital city of Cairo is Egypt','The capital city of Rome is Italy']
For a more complex example, suppose we have a model for a customer that looks something like this:
class Customer( models.Model ): first_name = models.CharField(max_length = 100, null = True) last_name = models.CharField(max_length = 100) username =models.Charfield(max_length =100) email = models.EmailField(max_length = 100) password = models.CharField(max_length =100)
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.
kwargs = {"first_name":"John","last_name":"Doe", "username': "johndoe","email"johndoe@gmail.com", "password":"1234"} new_user = User(**kwargs) new_user.save()
Here is how to perform a query of the customer we just created using kwargs.
filter_customer = { 'email':johndoe@gmail.com, 'username': johndoe, } Customer.objects.filter(**filter_customer)
Using Both Args and Kwargs in a Function
When using both args and kwargs in the same function definition, *args
must occur before **kwargs
.
class MyFunction(Foo): def __init__(self, *args, **kwargs): print 'my function' super(MyFunction, self).__init__(*args, **kwargs)
Example:
def Func(*args,**kwargs): for arg in args: print arg for item in kwargs.items(): print item
Remember args
should come before kwargs
.
def Func(*args,**kwargs): for arg in args: print arg for item in kwargs.items(): print item print Func(1,x=7,u=8)
Output 1 ('x', 7) ('u', 8)
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
andkwargs
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.
by Esther Vaati via Envato Tuts+ Code
No comments:
Post a Comment