Although it is a python argument, it is a positional argument, a keyword argument, and a keyword-only argument. I've been confused about getting multiple arguments using \ *, **, so I've organized them.
def f(a, b):
return a, b
f(1, 2)
=======================
(1, 2)
Arguments passed like a = 1 are called keyword arguments, and the order in which they are passed is irrelevant.
def f(a, b):
return a, b
f(b=2, a=1)
=======================
(1, 2)
You cannot pass a positional argument after a keyword argument.
def f(a, b):
return a, b
f(b=2, 1)
=======================
SyntaxError: positional argument follows keyword argument
You can use * to pass variadic arguments as tuples.
def f(a, b, *c):
return a, b, c
f(1, 2, 3, 4)
=======================
(1, 2, (3, 4))
You can use ** to pass variable length keyword arguments as a dict.
def f(a, b, **c):
return a, b, c
f(1, 2, x=3, y=4)
=======================
(1, 2, {'x': 3, 'y': 4})
Positional arguments cannot be assigned after arguments using \ *.
def f(a, *b, c):
return a, b, c
f(1, 2, 3, 4)
=======================
TypeError: f() missing 1 required keyword-only argument: 'c'
It seems that neither positional arguments nor keyword arguments can be assigned after **.
def f(a, **b, c):
return a, b, c
f(1, x=2, y=3, c=4)
=======================
SyntaxError: invalid syntax
You can now specify keyword-only arguments from Python 3. Arguments that come after the argument with * at the beginning can only be assigned as keyword arguments. In the following, c should be assigned as a keyword argument instead of a positional argument.
def f(a, *b, c):
return a, b, c
f(1, 2, 3, c=4)
=======================
(1, (2, 3), 4)
If you do not use variable-length positional arguments, specify * alone, and the subsequent arguments become keyword-only arguments.
def f(a, *, b):
return a, b
f(1, 2)
=======================
TypeError: f() takes 1 positional argument but 2 were given
def f(a, *, b):
return a, b
f(1, b=2)
=======================
(1, 2)
As I told you in the comments, it seems that there are also position-only arguments. https://docs.python.org/ja/3/tutorial/controlflow.html#positional-only-parameters
def f(x, y):
print(x, y)
f(y=456, x=123)
============================
123 456
def f(x, y, /):
print(x, y)
f(y=456, x=123)
============================
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got some positional-only arguments passed as keyword arguments: 'x, y'
f(x=123, y=456)
============================
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got some positional-only arguments passed as keyword arguments: 'x, y'
f(123, 456)
============================
123 456
When I was pointed out by other people, I thought that it might be a good study because it was embarrassing.
Recommended Posts