The world’s leading publication for data science, AI, and ML professionals.

Four Types of Parameters and Two Types of Arguments in Python

What are mandatory, optional, args, kwargs parameters and positional, keyword arguments

Image by Alexander Gresbek from Pixabay
Image by Alexander Gresbek from Pixabay

Different Programming languages have different syntaxes, but functions are one of the concepts that they can never avoid. When we mention functions or methods, in most of the cases we will pass arguments to these functions.

As one of the most flexible and dynamic programming languages, Python has some special rules about the function arguments passing. This is to enable the developers to do their job with maximum flexibility. However, it might not be quite easy for newbies to master all of these standards.

In this article, I’ll use examples to present all of these rules including mandatory, optional, keyword and non-keyword variable-length parameters, positional and keyword arguments.

0. Definition of Parameters and Arguments

Image by Gerd Altmann from Pixabay
Image by Gerd Altmann from Pixabay

I’m not a person who likes to memorise concepts or definitions. However, it is important to clarify some keywords that we are going to use a lot in this article for convenience.

It might be confusing when we say parameters and arguments. Some may think they are the same. However, it is commonly accepted that they are different as follows.

  • Parameters are the variables in the definition of a function. In other words, they exist in the function signature and will be used as variables in the function body.
  • Arguments are the actual values that were passed to the function when we call it. In other words, an argument could be an integer, a string, or any object.

1. Mandatory and Optional Parameters

Image by Pexels from Pixabay
Image by Pexels from Pixabay

In Python, we can easily define a function with mandatory and optional parameters. That is, when we initialise a parameter with a default value, it becomes optional. Otherwise, the parameter will be mandatory.

def my_func(man1, man2, opt1=0, opt2=''):
    print('man1:', man1)
    print('man2:', man2)
    print('opt1:', opt1)
    print('opt2:', opt2)

In the above example, man1 and man2 are mandatory because they are not initialised in the function definition. So, if we call the function without passing the arguments for them, it will throw an error.

For the optional parameters, we don’t have to pass any arguments. If we don’t, the default value will be used.

my_func(man1='a', man2='b')

1.1 All the mandatory parameters must be in the front

When we want to define a function with both mandatory and optional parameters, all the mandatory must be in front of all the optional ones.

def my_func(opt1=0, man1, man2, opt2=''):
    print('man1:', man1)
    print('man2:', man2)
    print('opt1:', opt1)
    print('opt2:', opt2)

This is because Python allows positional arguments which will be introduced in the next section. If it is allowed to define a function as above, when we pass a positional argument a, it is quite confusing that whether it is for the optional parameter opt1 or the mandatory parameter man1. It is too unreliable to decide this based on the number of arguments.

2. Positional Arguments & Keyword Arguments

Image by Gino Crescoli from Pixabay
Image by Gino Crescoli from Pixabay

2.1 What is a positional argument?

When we pass the arguments to a function. We don’t have to give the parameter name, as long as we will pass the arguments on their original position. That is the positional argument.

# my_func(man1, man2, opt1=0, opt2='')
my_func('a', 'b')

2.1 Keyword argument is positional-insensitive.

When an argument is not positional, it must be a keyword argument. When we explicitly mention the parameter name of an argument, it becomes a keyword argument.

Although we need to type more words, it might be more convenient when we use keyword arguments, because the position will be insensitive so we don’t need to care about the position.

# my_func(man1, man2, opt1=0, opt2='')
my_func(man2='a', man1='b')

In the above example, we pass man2 in front of man1.

2.2 Positional Arguments for both Mandatory and Optional Parameters

Positional arguments are not for mandatory parameters only. As long as we follow the position, it can be passed to optional parameters, too.

# my_func(man1, man2, opt1=0, opt2='')
my_func('a', 'b', 10, 'c')

2.3 Mix Positional and Keyword Arguments

We can also mix these two types of arguments. This is typically effective when we want to use a function with a few mandatory parameters but lots of optional parameters.

For example, we can pass two positional arguments to the two corresponding mandatory parameters, then skip the first optional parameter by using a keyword argument for the 2nd optional parameter.

# my_func(man1, man2, opt1=0, opt2='')
my_func('a', 'b', opt2='c')

2.4 Positional Arguments Must be in the Front

So far it was very flexible, right? Now, there is an important rule. That is, all the positional arguments must be in front of all the keyword arguments.

# my_func(man1, man2, opt1=0, opt2='')
my_func(man1='a', 'b', 10, opt2='c')
my_func(man1='a', man2='b', opt1=10, 'c')

The above two function call is invalid.

It makes sense why Python does not accept this. Suppose we have the four parameters p1, p2, p3 and p4.

  • If we have arguments a, b and p4=d, it is quite clear that p1=a, p2=b and p4=d.
  • If we have arguments p2=b and c, it is very confusing the argument c should be passed to p1 or p3. It needs more artificial rules to fix this and developers need to memorise it.

2.5 Enforcing keyword arguments

There is a trick in Python to enforce the function call to use keyword arguments rather than positional. We can add an asterisk in the function parameter list and any parameters to the right can only be passed by keyword argument.

def my_func(man1, *, man2):
    print(man1)
    print(man2)

If we try to use positional arguments for both of them, an error will occur.

my_func('a', 'b')

However, if we use keyword argument for man2, there will not be any problems.

my_func('a', man2='b')

3. Variable-Length Parameters

Image by Rudy and Peter Skitterians from Pixabay
Image by Rudy and Peter Skitterians from Pixabay

In Python, we can define two types of parameters that have variable lengths. They can be considered special types of optional parameters. In other words, there is no limit to the number of arguments that are passed to the parameter when we call this function.

3.1 Variable-length parameter – *args

The parameter *arg is such a syntax when we want to define a variable-length parameter.

def my_func(*args):
    print(args)

When we call this function, we can pass as many arguments as we wish. They will be accessible in the function as a tuple.

3.2 Keyword variable-length parameter – **kwargs

The other type of variable-length parameter is with keywords. The name kwargs stands for KeyWord ARGumentS.

def my_func(**kwargs):
    print(kwargs)

When we call the function and want to pass the arguments to the kwargs parameter, we need to specify the key and the values for each argument.

As shown in the example, the arguments will be received as a dictionary.

There is also a limitation that we can’t use any keys with special parameters. Basically, the keys have to comply with the syntax of Python variable names.

3.3 Combining keyword and non-keyword variable-length parameters

We can use both keyword and non-keyword variable-length parameters in a function. However, it is not allowed to put the keyword one in front of the non-keyword one.

# invalid
def my_func(**kwargs, *args):
    print(kwargs)
    print(args)

The other way around will work.

def my_func(*args, **kwargs):
    print(args)
    print(kwargs)
my_func('a', 'b', 'c', name='Chris', age=33)

This is quite similar to the rule that we can’t have keyword arguments in front of any positional arguments.

3.4 The "*args" and "**kwargs" can be renamed

I found that some learners don’t know that we can change the name of these two variable-length parameter names. They think these are reserved keywords in Python and enforced as syntax.

In fact, that’s not sure. We can use any names of them. The only important thing is to use the single asterisk for variable-length parameters and double asterisks for the keyword ones.

def my_func(*whatever, **does_not_matter):
    print(whatever)
    print(does_not_matter)
my_func('a', 'b', 'c', name='Chris', age=33)

4. Combine All Types of Parameters

Image by Gundula Vogel from Pixabay
Image by Gundula Vogel from Pixabay

4.1 Keyword variable-length parameter must be the last

We can use all 4 types of parameters in one function. Of course, there are some enforced rules.

Since the keyword variable-length parameter requires us to pass the arguments with keyword, it must be at the end of the parameters queue.

# Invalid
def my_func(**kwargs, man):
    print(args)
    print(kwargs)
def my_func(**kwargs, opt=0):
    print(args)
    print(kwargs)

4.2 A Trap when using all the 4 types

When we are using all four types of parameters in a single function, there is a trap that needs to be taken extra care of.

Suppose we define the function as follows.

def my_func(man, opt='default', *args, **kwargs):
    print(man)
    print(opt)
    print(args)
    print(kwargs)

When we are calling this function, the optional parameter and the variable-length parameter can be easily confused. Consider the following function call.

my_func('mandatory value', 'a', 'b', 'c', name='Chris', age=33)

The value a is considered as the value for the optional parameter. In this case, the optional parameter is not optional anymore. The following function call is valid if we want both a, b and c are passed to the args.

This issue can be solved by adjusting the position of the parameters when we define the function.

def my_func(man, *args, opt='default', **kwargs):
    print(man)
    print(opt)
    print(args)
    print(kwargs)

If we change the position of args and opt, we can call the function as follows so that the optional parameter is still optional.

my_func('mandatory value', 'a', 'b', 'c', name='Chris', age=33)

Summary

Image by Tibor Lezsófi from Pixabay
Image by Tibor Lezsófi from Pixabay

In this article, I have introduced all 4 types of parameters and 2 types of arguments in Python. The parameters are the variables in a function, whereas the arguments are the values passed to the parameters when calling the function.

The parameters can be mandatory or optional. For the optional parameters, they can have variable lengths with or without keywords. The arguments can be positional which rely on the position for decided with value is for which parameter. Or, we can explicitly pass the value with the keyword, which is the keyword argument.

Join Medium with my referral link – Christopher Tao

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)


Related Articles