Sub topic 4
Where each kind of parameter may appear
This chapter assumes you can define and call functions, know the basic built-in types (numbers, strings, lists, dicts, None), and can read a simple traceback. It also assumes you have seen default values such as def f(x=1) and keyword calls such as f(x=2).
A Python function signature is not a free-form list. Each kind of parameter has a fixed zone, and the zones must appear in a fixed order. Python checks this when it compiles the def, so a violation is a SyntaxError before any code runs.
The five kinds of parameter
Every parameter belongs to exactly one of these kinds:
- Positional-only: the caller must pass it by position. Declared before a
/marker. - Positional-or-keyword: the caller may use either style. This is the ordinary kind.
- Var-positional:
*args, which collects extra positional arguments into a tuple. - Keyword-only: the caller must pass it by name. Declared after
*or after*args. - Var-keyword:
**kwargs, which collects extra keyword arguments into a dict.
The full left-to-right order is:
Any zone may be empty. The zones that are present must still keep this order.
| Zone | Marker | Caller may pass | Defaults |
|---|---|---|---|
| Positional-only | before `/` | position only | follow the "no gap" rule below |
| Positional-or-keyword | between `/` and `*` | position or name | follow the "no gap" rule below |
| Var-positional | `*args` | extra positional values | none, always a tuple |
| Keyword-only | after `*` or `*args` | name only | any pattern |
| Var-keyword | `**kwargs` | extra named values | none, always a dict |
The later chapters cover the zones in detail. This chapter is about where each may sit and what Python rejects.
Seeing the zones with inspect
The inspect module reports the zone of each parameter as its kind. This signature uses every zone:
import inspect
def f(a, b=2, /, c=3, *args, d, e=5, **kwargs):
pass
for name, param in inspect.signature(f).parameters.items():
has_default = param.default is not param.empty
print(name, param.kind.name, has_default)
# a POSITIONAL_ONLY False
# b POSITIONAL_ONLY True
# c POSITIONAL_OR_KEYWORD True
# args VAR_POSITIONAL False
# d KEYWORD_ONLY False
# e KEYWORD_ONLY True
# kwargs VAR_KEYWORD FalseNote that d has no default but comes after c, which does. That is legal because d is keyword-only. The next section explains why.
The "no gap" rule for positional parameters
Among the parameters that can be passed by position (positional-only and positional-or-keyword together), once one has a default, every later one must also have a default.
def bad(a=1, b): # SyntaxError
return a, bCPython reports this as "non-default argument follows default argument". Newer versions word it as "parameter without a default follows parameter with a default". Both mean the same thing.
The reason is how positional binding works. Python fills parameters from left to right with the positional arguments the caller gave. If a had a default and b did not, a call like bad(5) would be ambiguous. Python would not know whether 5 means a with b missing, or b with a defaulted. The language avoids this by never allowing a gap: the parameters with defaults form a block at the right end of the positional group.
The rule applies across the / marker as well. The marker does not reset it:
def also_bad(a=1, /, b): # SyntaxError
return a, bThree ways to fix a gap
Suppose you want a required, b optional, and c required. Python rejects def f(a, b=1, c). You have three options:
# 1. Reorder so required parameters come first.
def f1(a, c, b=1):
return a, b, c
# 2. Give c a default too.
def f2(a, b=1, c=None):
return a, b, c
# 3. Make c keyword-only, which removes it from the positional group.
def f3(a, b=1, *, c):
return a, b, c
print(f1(10, 30)) # (10, 1, 30)
print(f2(10, c=30)) # (10, 1, 30)
print(f3(10, c=30)) # (10, 1, 30)Option 3 keeps the original order and keeps c mandatory. The cost is that callers must write c=.... That is often a benefit, because a call like f3(10, 1, c=30) is clearer than three bare values.
Keyword-only parameters are exempt
Keyword-only parameters are bound by name, never by position. A gap cannot make the binding ambiguous, so Python lifts the restriction. Defaults and non-defaults can be mixed in any order after the *:
def connect(host, *, timeout=10, retries, ssl=True):
return (host, timeout, retries, ssl)
print(connect("db.local", retries=3))
# ('db.local', 10, 3, True)Calling connect("db.local") without retries raises a TypeError, because retries is required even though it sits between two parameters with defaults.
Rules for the markers
The markers * and / have their own restrictions. Each of these definitions is a SyntaxError:
def e1(a, *, **kwargs): ... # bare * must be followed by a keyword-only parameter
def e2(*): ... # same reason
def e3(*args, *more): ... # only one * allowed
def e4(/, a): ... # / needs at least one parameter before it
def e5(a, /, b, /): ... # only one / allowed
def e6(*, a, /): ... # / must come before *
def e7(**kwargs, a): ... # nothing may follow **kwargs
def e8(a, **kwargs, **more): ... # only one ** allowed
def e9(*args, a=1, b): ... # this one is legal, see belowThe last line is a trap in the other direction. e9 is valid, because a and b are both keyword-only and may be mixed freely. Only the first eight are errors.
You can summarize the marker rules as follows:
/appears at most once and comes before*or*args.*or*argsappears at most once. A bare*needs at least one named parameter after it.**kwargsappears at most once and is always last. A trailing comma after it is allowed.*argsand a bare*are alternatives. You cannot use both in one signature, because*argsalready opens the keyword-only zone.
Lambdas follow the same rules, so lambda a, b=1, *, c: ... is valid and lambda a=1, b: ... is not.
The matching rule on the call side
Call syntax has an ordering rule too: positional arguments come before keyword arguments.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
print(greet("Ada", greeting="Hi")) # Hi, Ada
# greet(greeting="Hi", "Ada") # SyntaxError: positional argument follows keyword argumentPython processes a call in a fixed sequence. It fills positional slots from the left. Then it matches each keyword to a parameter name. Finally it checks that every required parameter has a value. Two situations raise a TypeError at this stage:
- A parameter receives a value twice:
greet("Ada", name="Bob")fails with "got multiple values for argument 'name'". - A required parameter receives nothing:
greet()fails with "missing 1 required positional argument: 'name'".
Because positional binding runs first, the order of positional-or-keyword parameters is part of your function's public interface. Swapping two of them breaks callers who pass them by position, even though the names are unchanged.
Why the order matters when you design
The zone order gives you a ladder of strictness. Moving a parameter toward the right makes callers more explicit and makes later changes safer:
- A positional-only parameter can be renamed freely, because no caller can use its name.
- A positional-or-keyword parameter cannot be renamed or reordered without breaking someone.
- A keyword-only parameter can be reordered freely, because callers refer to it by name.
If a function has several optional settings, the keyword-only zone is usually the right home for them. You avoid the no-gap rule, and callers cannot confuse the order.
Exercise
Which of these definitions is a SyntaxError, and why? (a) def f(a, b=1, , c): (b) def f(a=1, /, b=2): (c) def f(a=1, /, b): (d) def f(, a=1, b):
Show answer
Only (c) is a SyntaxError. Parameter b has no default but follows a, which has one, and both are in the positional group. The / marker does not reset the no-gap rule. (a) is valid because c is keyword-only. (b) is valid because both positional parameters have defaults. (d) is valid because keyword-only parameters may mix defaults and required parameters in any order.
Exercise
You have def send(msg, retries=3, timeout) and Python rejects it. Rewrite it so that timeout stays required, retries keeps its default, and the original parameter order is preserved. How must callers pass timeout?
Show answer
def send(msg, retries=3, *, timeout): ... Callers must pass timeout by keyword, for example send("hi", timeout=5) or send("hi", 2, timeout=5).