Sub topic 4
Putting parameters in the right order
This chapter assumes you can define and call functions, and that you know positional arguments, keyword arguments, default values, tuples and dictionaries. It also assumes you know what *args and **kwargs collect.
A function signature can mix several kinds of parameters. Python accepts them only in one fixed order, and that order decides where each value in a call ends up.
The required order
From left to right, a signature holds these groups. Every group is optional.
- Regular parameters without defaults.
- Parameters with defaults.
*args, which collects extra positional arguments.- Keyword-only parameters, with or without defaults.
**kwargs, which collects extra keyword arguments.
Here is a signature that uses all five groups:
def f(a, b=2, *args, c, d=4, **kwargs):
return a, b, args, c, d, kwargs
print(f(1, 2, 3, 4, c=5, e=6))
# (1, 2, (3, 4), 5, 4, {'e': 6})Python assigns the values in this order:
1fillsaand2fillsb.3and4have no named slot left, so they go into theargstuple.c=5matches the keyword-only parameterc.dis not supplied, so it keeps its default of4.e=6matches no named parameter, so it goes into thekwargsdictionary.
How a call fills the slots
Python processes a call in two passes.
- It fills the positional slots from left to right: regular parameters, then defaulted parameters. Any positional values left over go into
*args. - It matches keyword arguments by name. A name that matches a parameter fills it. A name that matches nothing goes into
**kwargs, or raises aTypeErrorif the function has no**kwargs.
Defaulted parameters that come before *args are positional slots. Extra positional values reach *args only after those slots are full:
def connect(host, port=80, *args, timeout=10, **options):
return host, port, args, timeout, options
print(connect("example.com"))
# ('example.com', 80, (), 10, {})
print(connect("example.com", 8080, "x", "y", timeout=5, retries=3))
# ('example.com', 8080, ('x', 'y'), 5, {'retries': 3})
print(connect("example.com", 80, 5))
# ('example.com', 80, (5,), 10, {})In the last call the author may have meant 5 as the timeout. Parameters after *args can only be set by keyword, so the 5 went into args and timeout kept its default. No error is raised.
Why keyword-only parameters exist
Anything after *args can only be set by name. If you want keyword-only parameters but no variable-length positional collection, use a bare *:
def resize(image, *, width, height):
return f"{image}: {width}x{height}"
print(resize("logo.png", width=64, height=32))
# logo.png: 64x32A call like resize("logo.png", 64, 32) raises a TypeError. The next chapters on keyword-only and positional-only parameters cover this in more detail.
Orderings Python rejects
Python checks the order when it compiles the function. A wrong order is a SyntaxError, not a runtime failure. These definitions are all invalid:
# def a(x=1, y): ... # SyntaxError: non-default argument follows default argument
# def b(**kwargs, x): ... # SyntaxError: arguments cannot follow var-keyword argument
# def c(*args, *more): ... # SyntaxError: * argument may appear only once
# def d(**kw1, **kw2): ... # SyntaxError: only one ** parameter is allowedThese lines are commented out so the file still runs. Remove the # to see each error.
One rule has an exception. Before *args, a parameter without a default cannot follow one with a default. After *args or a bare *, it can, because keyword-only parameters are matched by name and not by position:
def ok(a, b=1, *, c, d=4):
return a, b, c, d
print(ok(0, c=3)) # (0, 1, 3, 4)Here c has no default and follows b=1. Python accepts this, and c is still required.
Common errors from ordering
| Situation | Result |
|---|---|
| Required keyword-only parameter not supplied | `TypeError: f() missing 1 required keyword-only argument: 'c'` |
| Extra positional values and no `*args` | `TypeError: ... takes 2 positional arguments but 3 were given` |
| Unknown keyword and no `**kwargs` | `TypeError: ... got an unexpected keyword argument 'e'` |
| Same parameter given by position and by name | `TypeError: ... got multiple values for argument 'b'` |
The last row often surprises people. With f(a, b=2, *args, ...), the call f(1, 2, b=3, c=5) fails, because the second positional value already filled b.
Exercise
A function is defined as def run(cmd, retries=3, *flags, verbose=False, **env). What do cmd, retries, flags, verbose and env hold after the call run("ls", 1, "-a", "-l", verbose=True, HOME="/tmp")?
Show answer
cmd is "ls" and retries is 1, because the first two positional values fill the regular and defaulted parameters. flags is the tuple ("-a", "-l"), the leftover positional values. verbose is True, set by keyword. env is {"HOME": "/tmp"}, the keyword argument that matched no named parameter.