[PYTHON] Optional arguments and * args, ** kwargs

It is ok to put * args, ** kwargs after the optional arguments

It is possible to put arbitrary arguments before * args. The following code passes.

optionalarg.py


def foo(x=10, *args, **kwargs):
    return x, args, kwargs


print foo(12, 13, 14) 
#=> (12, (13, 14), {})

However, it is not possible to define a required argument after an optional argument. The following code will result in a syntax error.

syntaxerror.py


def foo(x=10, y, *args, **kwargs):
    return x, y, args, kwargs
# SyntaxError: non-default argument follows default argument

About the terms "arbitrary arguments" and "named arguments"

There are terms of optional arguments and named arguments, but how should we use them properly?

If you read "Dive In Python", you can guess as follows.

  1. "Optional argument" when used to define a function. The opposite concept of "essential arguments".
  2. "Named argument" to specify a name for the function call.

(Link: Translated version of cocoatomo because it is troublesome to read the English version) http://cocoatomo.iza-yoi.net/DIP/power_of_introspection/optional_arguments.html

Recommended Posts

Optional arguments and * args, ** kwargs
Notes on * args and ** kargs
python * args, ** kwargs Usage notes
Various arguments of functions in Python (positional arguments, optional arguments, variadic arguments, keyword arguments) def func (arg, * args, ** kwargs)
python3x: What do * args and ** kwargs appear as parameters mean?
Order of arguments of RegularGridInterpolator and interp2d
Mixed positional arguments, tuples and dictionaries
[Python] Function arguments * (star) and ** (double star)