- What are keyword arguments in Python?
- Types of Arguments
- Positional arguments
- Keyword arguments
- Fixed arguments vs. arbitrary arguments
- 5 Examples to Understand Keyword Arguments in Python
- What is Keyword Argument in Python?
- Why do we need Keyword Arguments?
- Example 1: Passing arguments to Keyword parameter
- Explanation
- Example 2: Passing keywords as Arguments
- Explanation
- Example 3: Keyword Arguments as Python Dictionary
- Explanation
- Example 4: Keyword Arguments Using Lambda Function
- Explanation
- Example 5: Keyword Arguments Python Argparse
- Explanation
- FAQs on Keyword Argument in Python
- Conclusion
What are keyword arguments in Python?
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
In Python, the terms parameter and argument are used interchangeably. However, there is a slight distinction between these two terms. Parameters are the input variables bounded by parentheses when defining a function, whereas arguments are the values assigned to these parameters when passed into a function (or method) during a function call.
def team(name, project):print(name, "is working on an", project)team("FemCode", "Edpresso")
In the example above, the function arguments are FemCode and Edpresso , whereas name and project are the function parameters.
Types of Arguments
There are two types of arguments: positional arguments and keyword arguments.
Positional arguments
Positional arguments are values that are passed into a function based on the order in which the parameters were listed during the function definition. Here, the order is especially important as values passed into these functions are assigned to corresponding parameters based on their position.
def team(name, project):print(name, "is working on an", project)team("FemCode", "Edpresso")
In these examples, we see that when the positions of the arguments are changed, the output produces different results. Though the code in example B isn’t wrong, the values that have been passed into the function are in the wrong order; thus, producing a result that does not match our desired output. Edpresso is the name of the project that is being worked on by the team, FemCode, not the other way around.
Now that the understanding is clear, let’s move on to keyword arguments.
Keyword arguments
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = .
Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
def team(name, project):print(name, "is working on an", project)team(project = "Edpresso", name = 'FemCode')
As you can see, we had the same output from both codes although, when calling the function, the arguments in each code had different positions.
With keyword arguments, as long as you assign a value to the parameter, the positions of the arguments do not matter.
However, they do have to come after positional arguments and before default/optional arguments in a function call.
Default arguments are keyword arguments whose values are assigned at the time of function definition. Optional arguments are default arguments that, based on the values assigned to them (e.g., None or 0), can be disregarded.
def team(name, project, members=None):team.name= nameteam.project= projectteam.members= membersprint(name, "is working on an", project)team(name = "FemCode", "Edpresso")
The ‘Wrong’ code above generated a syntax error. In Python, a syntax error is basically an error that goes against a rule in Python. In terms of the above error, Python did not approve of the order in which the arguments were passed.
def team(name, project):print(number, name,"are working on an", project)team("The two members of", "FemCode", "Edpresso")
The above code throws a TypeError that draws your attention to the number of allowed input arguments.
Is there a way around this such that we can pass in more arguments than is allowed? Let’s find out!
Fixed arguments vs. arbitrary arguments
Up until this point, we have been dealing with fixed function arguments. This simply means that the number of arguments we previously passed into functions were always limited to a specific quantity since we knew the number of arguments needed in advance. Sometimes, we do not know the number of arguments needed in advance; thus, we need to input more arguments than previously mentioned in the function definition. How do we go about this?
Python allows us to do this through certain special syntaxes that are collectively known as arbitrary arguments (or variable-length arguments). Here, unlike with fixed arguments, parameters are not specified by distinct individual names, but rather a general term to better encapsulate the shared attribute of the type of arguments being passed into the function. These syntaxes are of the forms:
5 Examples to Understand Keyword Arguments in Python
The functional programming approach gives us the ease of DRY (do not repeat yourself) programming. It is declarative programming where programs are created using sequential functions rather than writing all the statements. We can reuse them as per our needs. The function we create takes some input and returns some output or performs some operations. Now, the input it takes maybe as the arguments or directs from I/O. Today in this article, we will discuss one such method of feeding input to function, i.e., Keyword Argument in python. So, let’s go.
What is Keyword Argument in Python?
While defining a function, we set some parameters within it. We accept data in these parameters from function calls. Now, python provides the feature of accepting the parameters in several ways, e.g., positional arguments or keyword arguments. Keyword Arguments are used when we used to assign values to the function parameter as the key-value pair. In simple words, we use keyword arguments to assign values to a particular variable.
Why do we need Keyword Arguments?
While passing the arguments to functions, sometimes we know the number of parameters; contrary, it also happens that we don’t know the number of arguments. Both the scenarios are known as a fixed number of arguments or the arbitrary number of arguments respectively. Keyword arguments give us the ability to handle the arbitrary number of arguments as the key-value pair. The keyword arguments start with the “**” symbol followed by a variable name. Let’s see some of the examples to understand them better.
Example 1: Passing arguments to Keyword parameter
# Example on arguments and keyword arguments def func(a,*args,**kwargs): print(a) # Using arbitrary number of arguments as positional argument for arg in args: print(arg) # Using arbitrary number of arguments as keyword argument for key,value in kwargs.items(): print('<> = <>'.format(key,value)) func('Hii','I','am',name ='Python Pool', From ='Latracal Solution')
Hii I am name = Python Pool From = Latracal Solution
Explanation
So, in the above example, we created a function and then used three types of parameters to accept arguments. The first is a known parameter, the other is to accept a number of arbitrary arguments, and the last is to accept the number of keyword arguments. Then, we use for loop to access elements in the args and kwargs variables.
Example 2: Passing keywords as Arguments
def func(arg1,arg2,arg3,arg4): print(arg1) print(arg2) print(arg3) print(arg4) a = ("This","is",'positional','argument') b = # Passing positional argument to the function func(*a) print("---------") # Passing keyword argument to the function func(**b)
This is positional argument --------- This is keyword argument
Explanation
We created a tuple and a dictionary to pass them as the argument in the above example. This demonstrates that it is also easy to pass multiple values to function as arguments. We need to create variables and use “*” and “**” to specify the types of arguments.
Example 3: Keyword Arguments as Python Dictionary
So, have you ever thought about how these keyword arguments work? Or how the keywords map to their values when passing as the arguments. All this happens because the arguments we pass are passed in the form of a dictionary. It helps smooth mapping to every key for corresponding values without losing its entity. Let’s see the example.
def kwargs_to_dict(**kwargs): print(type(kwargs)) print(kwargs) kwargs_to_dict(name ='Python Pool', From ='Latracal Solution')
Explanation
So, in the above example, we have seen what the kwargs variable’s data type is and then printed it to get its content.
Example 4: Keyword Arguments Using Lambda Function
Besides all the features of the lambda function, it is also compatible with multiple parameters while working. Now, these parameters are either in the form of arguments or keyword arguments. Let’s see the example and learn how we can handle that.
x = (lambda **kwargs : sum(kwargs.values())/len(kwargs)) x(one = 1, two = 2, three = 3)
Explanation
So, in the above example, we can see that we created a lambda function x. And we used three keyword arguments for calling the function and then tried to find its average. To access each value from the dictionary, we used the values() function and then calculated its average.
Example 5: Keyword Arguments Python Argparse
#importing argparse module import argparse class KeyValue(argparse.Action): def __call__( self , parser, namespace, values, option_string = None): setattr(namespace, self.dest, dict()) for value in values: # split it into key and value key, value = value.split('=') # Adding it as dictionary getattr(namespace, self.dest)Pass keyword arguments python = value # Initializing parser object parser = argparse.ArgumentParser() # adding an arguments parser.add_argument('--kwargs',nargs='*',action = KeyValue) #parsing arguments args = parser.parse_args() # show the dictionary print(args.kwargs)
Explanation
In the above example, we first created a class that inherits from the agrparse class where we write a similar kind of code as explained in example 2 to add elements in the dictionary. Then we initialized an object for argparse.Argparser to hold the values of arguments from CLI. Then we added that element in the parser variable, parsed the arguments and had it in the args variable. And then printed the values of the dictionary.
FAQs on Keyword Argument in Python
Arguments or Positional arguments must be passed incorrectly, while keyword argument must be passed with the keyword that corresponds to some value.
Yes, it is passed as the dictionary, so the arguments are available as key-value pairs. Hence, Its order does not matter.
Keyword arguments are passed as arguments for the convenience of receiving the values corresponding to some key. In comparison, positional arguments are passed based on their position.
Conclusion
So, today in this article, we learned keyword arguments in python and how we can use them to pass the arguments to a function and accept them as the argument. I hope this article has helped you. Thank You.