Sub topic 4
Putting parameters in the right order
A function signature is a fixed sequence of slots. Python reads it left to right when you define the function, and it fills the slots in a set order when you call it. This chapter covers the legal order of parameters, how a call fills them, and which mistakes raise errors.
This chapter assumes you can define and call functions, use default values, and read tuples and dictionaries. It also assumes you know what *args and **kwargs collect, as covered in the previous chapters. Unpacking in calls comes in the next chapter. Keyword-only and positional-only parameters get a short treatment here and a fuller one later.
The canonical order
A signature can contain up to six kinds of parameters. When they appear together, they must appear in this order:
- Positional-only parameters, followed by a
/marker. - Regular parameters, which accept a value by position or by name.
- Regular parameters with defaults.
*args, or a bare*if you want keyword-only parameters without collecting extras.- Keyword-only parameters, with or without defaults.
**kwargs.
Most functions use only a few of these. You can skip any kind, but the ones you keep stay in this order.
The table below shows how each kind accepts values.
| Kind | Example | Accepts a value by position | Accepts a value by name |
|---|---|---|---|
| Positional-only | `a` before `/` | Yes | No |
| Regular | `b` | Yes | Yes |
| Regular with default | `b=2` | Yes | Yes |
| Variadic positional | `*args` | Yes, collects all extras | No |
| Keyword-only | `c` or `c=4` after `*` | No | Yes |
| Variadic keyword | `**kwargs` | No | Yes, collects all unmatched names |
The word "variadic" means the parameter accepts a variable number of values.
Seeing the kinds with `inspect`
Python records the kind of every parameter. The inspect module shows it, which is useful when you are unsure how a signature will behave.
import inspect
def f(a, b=2, *args, c, d=4, **kwargs):
return a, b, args, c, d, kwargs
print(inspect.signature(f))
for p in inspect.signature(f).parameters.values():
print(p.name, p.kind.name)The output is:
(a, b=2, *args, c, d=4, **kwargs)
a POSITIONAL_OR_KEYWORD
b POSITIONAL_OR_KEYWORD
args VAR_POSITIONAL
c KEYWORD_ONLY
d KEYWORD_ONLY
kwargs VAR_KEYWORDinspect.Parameter also defines POSITIONAL_ONLY for names before a /. Decorators and frameworks use these kind names to inspect and validate functions.
How a call fills the slots
For the call f(1, 2, 3, 4, c=5, e=6), Python works through these steps:
- It assigns positional values left to right to the positional parameters. Here
a=1andb=2. - It puts any remaining positional values into
*argsas a tuple. Hereargs=(3, 4). If the function has no*args, extra positional values raise aTypeError. - It matches each keyword argument to a parameter by name. Here
c=5. Only regular and keyword-only parameters can match. - It puts keyword arguments that match no parameter into
**kwargsas a dictionary. Herekwargs={'e': 6}. If the function has no**kwargs, these raise aTypeError. - It fills any parameter that is still empty from its default. Here
d=4. - If a parameter with no default is still empty, it raises a
TypeError.
The result is (1, 2, (3, 4), 5, 4, {'e': 6}).
Order matters in step 1. Positional values fill positional slots before *args sees anything, so you cannot skip a regular parameter to reach *args. To put anything into *args, the caller must also supply every regular parameter before it.
A worked example
Here is a function that sends a message to any number of recipients, with a few options.
def send(message, *recipients, retries=3, urgent=False, **metadata):
return {
"message": message,
"recipients": recipients,
"retries": retries,
"urgent": urgent,
"metadata": metadata,
}
print(send("hi", "ann", "bo", urgent=True, source="cli"))The output is:
{'message': 'hi', 'recipients': ('ann', 'bo'), 'retries': 3, 'urgent': True, 'metadata': {'source': 'cli'}}The call fills the slots like this:
messagetakes"hi".*recipientscollects"ann"and"bo"into a tuple.urgent=Truematches a keyword-only parameter by name.source="cli"matches nothing, so it lands inmetadata.retrieswas not supplied and keeps its default of3.
The options retries and urgent are placed after *recipients on purpose. They can only be set by name, so a caller can never confuse a recipient with an option. The next section shows what happens when you place them before *recipients.
Defaults before `*args` get swallowed
Suppose the same function put retries before *recipients.
def send_v2(message, retries=3, *recipients):
return message, retries, recipients
print(send_v2("hi", "ann", "bo"))The output is ('hi', 'ann', ('bo',)). The value "ann" filled retries because positional values fill regular parameters first. The function now has a recipient stored in the retry count.
This is a design problem more than a syntax problem. Any default placed before *args can only be left alone if the caller passes no extra positional values. For that reason, put optional settings after *args as keyword-only parameters, as send does.
Keyword-only parameters, with and without defaults
Regular parameters must put all non-default parameters before default ones. Keyword-only parameters do not have this restriction, because they are matched by name and not by position.
def connect(host, *, port=5432, user, timeout=10):
return host, port, user, timeout
print(connect("db.local", user="admin"))
print(connect("db.local", timeout=5, user="admin", port=6543))The output is:
('db.local', 5432, 'admin', 10)
('db.local', 6543, 'admin', 5)Here user is a required keyword-only parameter that follows port, which has a default. That would be illegal for regular parameters. A bare * marks where the keyword-only section starts when you do not want to collect extra positional values. A function with a bare * and no *args rejects any extra positional value with a TypeError.
Positional-only parameters and the `/` marker
A / in the signature makes every parameter before it positional-only. Callers cannot pass these by name.
def h(a, /, **kwargs):
return a, kwargs
print(h(1, a=2))The output is (1, {'a': 2}). Because a is positional-only, the name a is free for **kwargs to collect. Without the /, the same call would raise TypeError: h() got multiple values for argument 'a'. This is the main practical reason to use / with **kwargs. A function can then accept arbitrary keys, including ones that match its own parameter names.
Syntax errors from wrong order
Some orderings are rejected when Python compiles the function, before any call happens. The following code checks four of them without stopping the program.
bad_signatures = [
"def f(a=1, b): pass",
"def f(**kwargs, a): pass",
"def f(*args, *more): pass",
"def f(*, **kwargs): pass",
]
for source in bad_signatures:
try:
compile(source, "<demo>", "exec")
except SyntaxError as error:
print(f"{source!r} -> {error.msg}")Each one prints a SyntaxError message. The exact wording changes between Python versions, so do not rely on the text. The four rules behind these errors are:
- A regular parameter without a default cannot follow one with a default.
**kwargsmust be the last parameter.- A signature can have only one
*args(or bare*) and only one**kwargs. - A bare
*must be followed by at least one named keyword-only parameter.
Errors that appear at call time
Valid signatures still produce errors when a call does not fit them. These are all TypeError.
def f(a, b=2, *args, c, d=4, **kwargs):
return a, b, args, c, d, kwargs
calls = [
lambda: f(1, c=3),
lambda: f(1, 2, 3, 4),
lambda: f(c=3),
lambda: f(1, a=2, c=3),
]
for call in calls:
try:
print(call())
except TypeError as error:
print("TypeError:", error)The output is:
(1, 2, (), 3, 4, {})
TypeError: f() missing 1 required keyword-only argument: 'c'
TypeError: f() missing 1 required positional argument: 'a'
TypeError: f() got multiple values for argument 'a'Each call shows a different mistake:
f(1, c=3)is valid. The unused slots take their defaults, andargsandkwargsare empty.f(1, 2, 3, 4)supplies four positional values. Two fillaandb, and two go toargs. The required keyword-onlycis still empty.f(c=3)gives no value for the required parametera.f(1, a=2, c=3)givesaa value by position and again by name.
The "multiple values" error is the one most often seen with ** unpacking. It is covered in the pitfalls chapter.
Choosing an order for your own functions
When you design a signature, these guidelines keep calls readable.
- Put required parameters first, then optional ones.
- If a function takes a variable number of items of the same kind, make that
*args. Keep options out of the positional slots. - Make options keyword-only. Calls such as
send("hi", "ann", urgent=True)are clearer than ones relying on position. - Use
**kwargswhen you accept arbitrary names or forward them to another function. If you only expect a known set of options, list them as named keyword-only parameters. Misspelled names then raise an error instead of disappearing into a dictionary. - Use
/only when a parameter name is not part of your public interface, or when you need the**kwargscollision behavior shown above.
Summary
The legal order is positional-only, then /, then regular, then defaults, then *args or bare *, then keyword-only, then **kwargs. At call time, positional values fill slots from the left, extras go to *args, keywords match by name, unmatched keywords go to **kwargs, and defaults fill the rest. Options placed before *args can be filled by accident, so place them after it.
Exercise
What does def f(a, b=1, *args, c, **kwargs) return for the call f(1, 2, 3, c=4, d=5)? Write the values of a, b, args, c and kwargs.
Show answer
a=1, b=2, args=(3,), c=4, kwargs={'d': 5}. The first two positional values fill a and b, the third goes to args, c matches by name, and d matches nothing so it goes to kwargs.
Exercise
A function is defined as def log(level="info", *messages): .... A caller runs log("disk full", "retrying") and finds that the level is "disk full". Rewrite the signature so that the level can only be set by name and defaults to "info".
Show answer
def log(messages, level="info"): ... Placing level after messages makes it keyword-only. The call log("disk full", "retrying") then puts both strings into messages, and level stays "info" unless the caller writes level="warn".
Exercise
Why does def h(a, /, **kwargs): return a, kwargs accept the call h(1, a=2), while def h(a, **kwargs) raises a TypeError for the same call?
Show answer
With the /, the parameter a is positional-only, so the name a is not matched to it and the keyword a=2 goes into kwargs. Without the /, a=2 targets the regular parameter a, which already received 1 by position, so Python raises "got multiple values for argument 'a'".