args and kwargs
suggest changeRemarks
There are a few things to note:
-
The names
argsandkwargsare 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
*argsparameter or more than one**kwargsparameter (though neither is required)def func(*args1, *args2): # SyntaxError: * argument may appear only once # def test(**kwargs1, **kwargs2): # SyntaxError: arguments cannot follow var-keyword argument -
If any positional arguments follow
*args, they are keyword-only arguments that can only be passed by name. A single star may be used instead of*argsto 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 -
**kwargsmust come last in the parameter list.def test(**kwargs, *args): # SyntaxError: arguments cannot follow var-keyword argument
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents