args and kwargs
suggest changeRemarks
There a few things to note:
- The names
args
andkwargs
are used by convention, they are not a part of the language specification. Thus, these are equivalent:def func(*args, **kwargs): print(args) print(kwargs) # def func(*a, **b): print(a) print(b)
- You may not have more than one
args
or more than onekwargs
parameters (however they are not required)def func(*args1, *args2): # File "<stdin>", line 1 # def test(*args1, *args2): # ^ # SyntaxError: invalid syntax # def test(**kwargs1, **kwargs2): # File "<stdin>", line 1 # def test(**kwargs1, **kwargs2): # ^ # SyntaxError: invalid syntax
- If any positional argument follow
*args
, they are keyword-only arguments that can only be passed by name. A single star may be used instead of*args
to force values to be keyword arguments without providing a variadic parameter list. Keyword-only parameter lists are only available in Python 3.def func(a, b, *args, x, y): print(a, b, args, x, y) func(1, 2, 3, 4, x=5, y=6) #>>> 1, 2, (3, 4), 5, 6 # def func(a, b, *, x, y): print(a, b, x, y) func(1, 2, x=5, y=6) #>>> 1, 2, 5, 6
**kwargs
must come last in the parameter list.def test(**kwargs, *args): # File "<stdin>", line 1 # def test(**kwargs, *args): # ^ # SyntaxError: invalid syntax
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents