[PYTHON] Variadic argument

Variadic argument

Variadic arguments are, as the name suggests, arguments whose length can be freely changed. Therefore, it is a function that can handle any number of arguments. It can be defined by adding * or ** to the function argument. Only one variable length argument can be defined for each.

easy_sample.


$ python3
Python 3.5.0 () 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def print_parameters(*arguments, **keyword_arguments):
...     print('args =', arguments)
...     print('kwargs =', keyword_arguments)
... 
>>> print_parameters(1,2,3,4, a=4, b=3, c='hoge')
args = (1, 2, 3, 4)
kwargs = {'c': 'hoge', 'b': 3, 'a': 4}

It looks like this for easy usage. (* Args are arguments and kwargs are keyword arguments) If you add * like * arguments, ordinary arguments will be combined into tuple. If you add ** like ** keyword_arguments, the keyword arguments will be combined into dict. Of course, you cannot write anything that starts with a half-width number on the left side of =.

Mix ordinary arguments

If there is something that you absolutely receive as an argument. It can be placed before or after the argument with *. Since there is a rule to write the keyword argument at the end of the argument, no argument can be written after **. As a caveat at this time, the argument placed before the argument with * cannot be written as a keyword argument. The argument after * must be written as a keyword argument.

sample.


>>> def print_parameters(flag, *arguments, length, **keyword_arguments):
...     print(flag, length)
...     print('args =', arguments)
...     print('kwargs ='keyword_arguments)
>>> print_parameters(True,1,2,3,4,length=4, args=4, a=3, c='hoge')
True 4
(1, 2, 3, 4)
{'args': 4, 'c': 'hoge', 'a': 3}
>>> print_parameters(True, length=0)
True 0
args = ()
kwargs - {}

Error example: When flag is used as a keyword argument
>>> print_parameters(1, 2, 3, 4,flag=False, length=4, args=4, a=3, c='hoge')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: print_parameters() got multiple values for argument 'flag'

Error example: When length is not written as keyword argument
>>> print_parameters(True,1,2,3,4,4, args=4, a=3, c='hoge')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: print_parameters() missing 1 required keyword-only argument: 'length'

In this way, it spits out an error. Probably, the argument is processed from the front, so in the case of flag, 1 was assigned first, but I tried to mess with flag = False and flag again with the keyword argument, so an error occurred. .. In the case of length, * arguments receives all 1,2,3,4,4, so I think that there is nothing in length. At this time, if you set the default value when defining the function in length, no error will occur.

To pass the contents of list (tuple) or dict as an argument

From here on, we're using variadic arguments, but it's a basic story, not much related to variadic arguments. If you pass it normally,

list_dict.


>>> def print_parameters(flag, *arguments, length, **keyword_arguments):
...     print(flag, length)
...     print('args =', arguments)
...     print('kwargs =`, keyword_arguments)
>>> print_parameters(True, [1,2,3,4,5], {'a':5, 'b':2} , length=2)
True 2
args = ([1, 2, 3, 4, 5], {'b': 2, 'a': 5})
kwargs = {}

List and dict are included in * argument as one variable each. If you want to pass list (tuple) with each element as an argument

*list.


>>> print_parameters(*[True, 1,2,3,4,5], 6, length=6)
True 6
args = (1, 2, 3, 4, 5, 6)
kwargs = {}

In this way, you can pass each one by prepending * to list. Next, if you want to pass dict as a keyword argument

**dict.


>>> print_parameters(**{'flag':True, 'length':5, 'a':0, 'b':1}, c=1, d=3)
True 5
args = ()
kwargs = {'c': 1, 'd': 3, 'b': 1, 'a': 0}

In the case of dict, you can mix it with the keyword argument by adding**. The keywords (flag and length) originally defined in the function are assigned to it, otherwise they are in keyword_arguments. dict will pass all the keys if you add only one*.

*dict.


>>> dic = {'flag':True, 'length':0, 'a':1, 'b':2}
>>> print_parameters(True, *dic, length=4)
True 4
args = ('flag', 'b', 'a', 'length')
kwargs = {}

I feel like this.

Summary

This time, I wrote about variadic arguments. ** puts the keyword arguments into a dict. (Except for the defined keyword argument) * bundles the arguments into tuples. Write the keyword arguments together on the far right. Only one variable-length argument and one keyword variable-length argument can be written in one function.

Recommended Posts

Variadic argument
Variadic argument that accepts one or more arguments
Keyword argument routing