Sub topic 4
Where each kind of parameter may appear
This chapter assumes you can define functions with default values and call them with positional and keyword arguments. Python checks the order of parameters when it compiles the def statement. A wrong order is a SyntaxError, so the program never starts.
The order, left to right
A parameter list can contain up to six kinds of parameter. They must appear in this order:
- Positional-only parameters, followed by the
/marker. - Positional-or-keyword parameters. This is the ordinary kind.
- Either
*argsor a bare*. - Keyword-only parameters.
**kwargs.
Every part is optional, but the ones you use keep this order.
The next table shows how each kind can be passed in a call.
| Kind | Position in the list | Can be passed by position | Can be passed by keyword |
|---|---|---|---|
| Positional-only | Before `/` | Yes | No |
| Ordinary | Between `/` and `*` | Yes | Yes |
| `*args` | After ordinary parameters | Collects extras | No |
| Keyword-only | After `*` or `*args` | No | Yes |
| `**kwargs` | Last | No | Collects extras |
One function with every kind
def demo(a, b=2, /, c=3, *, d, e=5, **extra):
return (a, b, c, d, e, extra)
print(demo(1, d=4))
print(demo(1, 20, 30, d=4, e=6, z=7))The output is:
(1, 2, 3, 4, 5, {})
(1, 20, 30, 4, 6, {'z': 7})Here a and b are positional-only, c is ordinary, and d and e are keyword-only. Any unknown keyword, such as z, goes into extra.
The defaults rule
Among the positional parameters (positional-only and ordinary together), a parameter without a default cannot come after one with a default. Python would not know which arguments to leave unfilled.
# def bad(a=1, b): # SyntaxError: a parameter without a default
# pass # follows a parameter with a default
def good(a, b=1):
return a + bKeyword-only parameters are exempt from this rule. They are matched by name, so there is no ambiguity. That is why d above is required even though b and c have defaults before it.
Rules for the markers
/must come before*, and each marker can appear only once.- A bare
*must be followed by at least one keyword-only parameter.def f(a, *):is a SyntaxError. - A function can have only one
*args, and only one**kwargs. - Nothing can come after
**kwargs, not even a trailing*or another parameter. *argsalready does the job of a bare*. Anything after*argsis keyword-only, so you don't write both.
def total(first, *numbers, scale=1):
return (first + sum(numbers)) * scale
print(total(1, 2, 3)) # 6
print(total(1, 2, 3, scale=2)) # 12scale can only be set by name. A fourth positional argument would be collected into numbers, not assigned to scale.
Exercise
Is this definition valid? If not, fix it with the smallest change. def f(x, y=1, z): return x + y + z
Show answer
It is invalid, because z has no default but follows y, which does. Two fixes work. Give z a default: def f(x, y=1, z=2). Or make z keyword-only: def f(x, y=1, *, z). The second keeps z required.