Various arguments of functions in Python (positional arguments, optional arguments, variadic arguments, keyword arguments) def func (arg, * args, ** kwargs)

Preface

This time is a small story. Again, many people don't know how to use it at work, so I thought I'd write it down. Especially variadic and keyword arguments. Probably because it's not in other major languages ... Well, if you search, you can find as many as you want ...

How to create a user-defined function in Python

I will do it with Python 3.X system. This is the basis.

##Function definition *'argument'Is the variable name
def func('argument'):
    # process
    return ret

if __name__ == '__main__':
    #Function call *'argument'Is actually a variable or value
    x = func('argument') 

This time, how to pass or receive the argument here. The story that Python can receive this way.

Positional argument

A method of receiving positional arguments as they are, in order. This is unchanged in other programming languages.

Sample code and description

code


def func(arg1, arg2, arg3):
    return (arg1 * 3.0) + (arg2 * 2.0) + (arg3 * 1.0)

if __name__ == '__main__':
    y = func(4, 5, 6)
    print(y)

output


28.0

The caller passes 4,5,6 in order, respectively. Therefore, on the receiving side, it is passed according to the position (order). arg1 = 4、arg2 = 5、arg3 = 6 Therefore, the processing content of this function is 4 * 3 + 5 * 2 + 6 * 1 = 28.

Optional arguments

Nothing happens, define the arguments that you don't have to specify at the time of calling.

Sample code and description

code


def func(arg=1):
    print(arg)

if __name__ == '__main__':
    func()
    func(99)

output


1
99

When the argument arg is omitted at the time of definition and is called, the default value is determined as to how to handle it. By setting "arg = 1", when omitted, the processing in the function starts with 1 in arg.

Since the argument is omitted in the first call, the default value of 1 is output. Since the second time is not omitted, the passed 99 is output.

Variadic argument

Variadic argument, as the name implies, is a method of receiving an unspecified number of n arguments. Add one * (asterisk) to the argument name. This asterisk is not needed when handling within a function. I've never seen it in other languages.

Sample code and description

code


def func(*args):
    for i, v in enumerate(args):
        print('args[%d] = %s' % (i, v))

if __name__ == '__main__':
    func((1, 2), 3, 4, (5, 6), 7, 8)

output


args[0] = (1, 2)
args[1] = 3
args[2] = 4
args[3] = (5, 6)
args[4] = 7
args[5] = 8

The function definition provides only one args, but the caller passes four arguments. The way the caller passes it is also a little tricky. The first (1, 2) is now one Tuple, and (5, 6) is the same. Other than that, one numerical value has one argument, so as you can see from the output, there are six arguments.

On the receiving side, multiple arguments are passed to args as one Tuple. Since Tuple is iterable, it is a standard output that is shifted by one in a for loop. Since it is a Tuple, you can refer to the argument value at any position with args [i] in the function.

Of course, you can't make two as shown below. I don't know where the first variable length is and where the second variable length is.

def func(*args1, *args2):
    print(args1, args2)

Keyword arguments

The keyword argument is also a variable length argument, and the difference from the variable length argument is that it has a keyword. ・ ・ ・ ・ ・ ・ ・ Difficult to explain in words. The variadic argument is Tuple, while the keyword argument is Dictionary.

Sample code and description

code


def func(**kwargs):
    print(kwargs['arg1'], kwargs['args'])
    # print(kwargs)
    
if __name__ == '__main__':
    func(arg1=1, args=(2, 3, 4), arg2=5)

output


1 (2, 3, 4)

In the keyword argument, the caller passes it in the form of "keyword = value". In this func, kwargs is a keyword argument, and "arg1" and "args" are output as standard in the function. The caller also specifies arg2, but nothing is done because it is not handled in the function.

Since it has been passed, the commented out print (kwargs) outputs the Dictionary as shown below.

python


{'arg1': 1, 'args': (2, 3, 4), 'arg2': 5}

I have received arg2 = 5 properly.

By the way, like variable length arguments, you can't make two. I don't know which keyword argument.

Use in combination

Note that when using these in combination, the position is important except for the keyword argument.

Combination of variadic and keyword arguments
This is a common combination.

code


def func(*args, **kwargs):
    print('args = ', args)
    print('kwargs = ', kwargs)
    
if __name__ == '__main__':
    func(1, 2, 3, 4, arg1=5, arg2=6)

Four non-keyword values in the first half of the call are passed to the variadic args. Arguments with keywords are passed to args in the second half. When using this combination as a constraint, it must be a variable length argument first and then a keyword argument.

code


def func(**kwargs, *args):
    ~~~~~

This is an invalid syntax.

Combination of positional and variadic arguments
If the positional argument is written before the variable length argument, it becomes the positional argument.

code


def func(arg1, arg2, *args):
    print('arg1 = ', arg1)
    print('arg2 = ', arg2)
    print('args = ', args)
    
if __name__ == '__main__':
    func(1, 2, 3, 4, 5)

output


arg1 =  1
arg2 =  2
args =  (3, 4, 5)

It's not too difficult. The first two are positional arguments, so 1 and 2 are arg1 and arg2, respectively. The rest is tupled into variadic arguments,

Combination of positional and keyword arguments
This doesn't bother me too much. All positional arguments are defined first, and keyword arguments are last.

code


def func(arg1, arg2, **kwargs):
    print('arg1 = ', arg1)
    print('arg2 = ', arg2)
    print('kargs = ', kwargs)
    
if __name__ == '__main__':
    func(1, 2, kwarg1=2, kwarg2=3)

output


arg1 =  1
arg2 =  2
kargs =  {'kwarg1': 2, 'kwarg2': 3}
Optional and keyword argument combination
This is also simple. Define the keyword argument at the end.

code


def func(arg=1, **kwargs):
    print('arg = ', arg)
    print('kargs = ', kwargs)
    
if __name__ == '__main__':
    func(kwarg1=2, kwarg2=3)
    func(99, kwarg1=100, kwarg2=101)

output


arg =  1
kargs =  {'kwarg1': 2, 'kwarg2': 3}
arg =  99
kargs =  {'kwarg1': 100, 'kwarg2': 101}

When calling, it feels the same as when combining positional arguments and keyword arguments. However, the positional argument part can be omitted. Of course, if omitted, the default value.

Combination of optional and variadic arguments
This needs attention. The order of the arguments can be used by setting the variable-length argument first and the following optional arguments.

code


def func(*args, arg=1):
    print('arg = ', arg)
    print('args = ', args)
    
if __name__ == '__main__':
    func(1, 2, 3, 4, arg=5)
    func(5, 6, 7, 8)

output


arg =  5
args =  (1, 2, 3, 4)
arg =  1
args =  (5, 6, 7, 8)

Furthermore, when calling, the argument name must be specified as an optional argument like a keyword argument. The default value is 1 if omitted at the time of calling.

Points related to object orientation

If you're experienced in other languages, you might have wondered, "Hmm? Function overload?" In Python, you can pass an unspecified number of arguments in this way. In addition, the data types of variables are also dynamically typed, which is found in other object-oriented programming languages. ** There is no overloading (overloading) in Python. ** **

By making full use of the method of passing arguments this time and changing the processing content in one function, you can do something like overloading. However, the function name is the same, and the real overload created by the number of arguments and different types cannot be done.

If you try to force it in a way you're used to in other languages ...

overload


def func(arg):
    return arg

def func(arg1, arg2):
    return arg1, arg2

if __name__ == '__main__':
    ret = func(1)

output


TypeError: func() missing 1 required positional argument: 'arg2'

Overloads with different numbers of arguments in other languages, but in Python this is an error. However, in Python, which is an interpreter, the func written in the second overwrites the first, so ** The content of the error is "arg2 is not specified". Caution. ** **

Recommended Posts

Various arguments of functions in Python (positional arguments, optional arguments, variadic arguments, keyword arguments) def func (arg, * args, ** kwargs)
Optional arguments and * args, ** kwargs
Keyword arguments for Python functions
Summary of various for statements in Python
Example of taking Python> function> * args as arguments