Sub topic 1
Quick recap: positional and keyword arguments
Prerequisites
This chapter assumes you can already do the following:
- Define a function with
defand call it. - Use default parameter values such as
def f(x=1). - Read and build tuples and dictionaries, including iterating over a dictionary with
.items().
Everything else is reviewed here. This chapter sets up the vocabulary and the matching rules that the later chapters on *args, **kwargs and unpacking depend on. You may know most of it already. The precise rules for how Python matches call values to parameters are what make the rest of the tutorial predictable, so read it as a refresher on those rules.
Parameters and arguments
Two words are easy to mix up:
- A parameter is a name in the function definition. It is a slot that waits for a value.
- An argument is a value in the function call. It fills a slot.
def describe_pet(name, species, age=1): # name, species, age are parameters
return f"{name} is a {species}, age {age}"
print(describe_pet("Rex", "dog", 4)) # "Rex", "dog", 4 are argumentsOutput:
Rex is a dog, age 4When Python runs a call, it performs binding. It creates a fresh local variable for each parameter and assigns it one of the call's arguments, or the default if the caller supplied none. The rest of this chapter describes how Python decides which argument goes into which slot.
Positional arguments
A positional argument is matched to a parameter by its position. The first argument goes to the first parameter, the second to the second, and so on.
def describe_pet(name, species, age=1):
return f"{name} is a {species}, age {age}"
print(describe_pet("Rex", "dog"))
print(describe_pet("Rex", "dog", 4))
print(describe_pet("dog", "Rex"))Output:
Rex is a dog, age 1
Rex is a dog, age 4
dog is a Rex, age 1The last call shows the main weakness of positional arguments. Python cannot tell that you swapped two values. If the types are the same, the code runs and gives a wrong answer. Positional arguments are compact, but the reader of a call such as resize(img, 640, 480, True) has to look up the definition to know what True means.
Keyword arguments
A keyword argument is written as name=value in the call. Python matches it to the parameter with that name, and position no longer matters.
def describe_pet(name, species, age=1):
return f"{name} is a {species}, age {age}"
print(describe_pet(species="cat", name="Tom"))
print(describe_pet("Tom", age=3, species="cat"))Output:
Tom is a cat, age 1
Tom is a cat, age 3Keyword arguments make calls self-documenting and let you skip optional parameters in the middle of a signature. They also tie callers to parameter names. Renaming a parameter in a public function breaks every caller that used the old name as a keyword.
Mixing the two
You can combine both styles in one call, with one rule: positional arguments must come before keyword arguments. The reverse is a SyntaxError, which Python reports before the program starts running.
def describe_pet(name, species, age=1):
return f"{name} is a {species}, age {age}"
print(describe_pet("Rex", species="dog", age=4)) # fine
# describe_pet(name="Rex", "dog") # SyntaxError: positional argument follows keyword argumentOutput:
Rex is a dog, age 4A call may only fill each parameter once. If a positional argument has already filled name, then name="Bob" in the same call is a conflict. You will see this error again when ** unpacking is introduced.
Default values
A parameter with a default is optional. If the caller does not supply it, Python binds the default. Parameters without defaults are required.
A required parameter cannot come after a parameter with a default in an ordinary signature:
# def broken(a=1, b): # SyntaxError: non-default argument follows default argument
# ...The reason is that positional matching would be ambiguous. If a is optional but b is not, a call with one positional argument would have to decide which parameter it fills. Python avoids the question by requiring required parameters first. Later chapters show how keyword-only parameters relax this rule.
Defaults are evaluated once
A default expression runs once, when the def statement executes. It does not run on each call. For immutable values such as numbers and strings, this makes no difference. For a mutable value such as a list, every call that uses the default shares the same object:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))Output:
['a']
['a', 'b']The second call did not start with an empty list. It reused the list created at definition time. The standard fix is a None sentinel:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))Output:
['a']
['b']How Python matches a call to a signature
For a function with only ordinary parameters and defaults, the matching algorithm is short:
- Fill parameters from left to right with the positional arguments.
- For each keyword argument, find the parameter with that name and fill it. If the slot is already filled, raise a
TypeError. If no parameter has that name, raise aTypeError. - For each parameter still empty, use its default. If it has none, raise a
TypeError.
You can watch this process with the inspect module. Signature.bind() performs the matching without calling the function, and apply_defaults() fills in the remaining slots:
import inspect
def describe_pet(name, species, age=1):
return f"{name} is a {species}, age {age}"
signature = inspect.signature(describe_pet)
print(signature)
bound = signature.bind("Rex", species="dog")
bound.apply_defaults()
print(bound.arguments)Output:
(name, species, age=1)
{'name': 'Rex', 'species': 'dog', 'age': 1}This is a useful tool when you are unsure how a call will be interpreted. It uses the same rules as the interpreter and raises the same kind of TypeError on a bad call.
The four common call errors
Each step of the algorithm has a matching error. All four are TypeError, and the message names the function and the parameter involved.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
bad_calls = [
lambda: greet(),
lambda: greet("Ada", "Hi", "extra"),
lambda: greet("Ada", greting="Hi"),
lambda: greet("Ada", name="Bob"),
]
for call in bad_calls:
try:
call()
except TypeError as error:
print(error)Output:
greet() missing 1 required positional argument: 'name'
greet() takes from 1 to 2 positional arguments but 3 were given
greet() got an unexpected keyword argument 'greting'
greet() got multiple values for argument 'name'| Message | Cause | Typical fix |
|---|---|---|
| `missing 1 required positional argument` | A parameter without a default received nothing. | Pass the value, or give the parameter a default. |
| `takes from 1 to 2 positional arguments but 3 were given` | More positional arguments than parameters. | Remove the extra value, or accept extras (see the next chapter). |
| `got an unexpected keyword argument` | The keyword matches no parameter, often a typo. | Fix the name, or accept arbitrary keywords (see the chapter after that). |
| `got multiple values for argument` | The same parameter was filled twice. | Pass the value only once. |
The exact wording varies slightly between Python versions. Python 3.10 and later include the function name as written above, and older versions say the same thing in a slightly different form. The categories are stable.
Reading call sites
Some habits make code with both styles easier to maintain.
- Pass the first one or two obvious arguments positionally, and use keywords for the rest. For example,
open(path, mode="rb")reads better thanopen(path, "rb")for readers who do not remember the order. - Use keywords for booleans and numeric flags.
connect(host, timeout=5, retry=False)is much clearer thanconnect(host, 5, False). - Keep the same order in your signatures across related functions, so positional calls stay predictable.
- Treat parameter names as part of the public interface for any function others call.
The standard library follows these habits. sorted(items, key=len, reverse=True) passes the data positionally and the options by keyword. In fact sorted accepts key and reverse only by keyword, a feature covered in the chapter on keyword-only and positional-only parameters.
Why a fixed signature is sometimes not enough
Every function so far declares exactly the parameters it accepts. Three situations make that restriction awkward:
- The number of inputs varies. A function such as
printaccepts any number of values:print("a"),print("a", "b", "c"). - The set of options is open-ended. A function that builds an HTML tag may allow any attribute name, such as
id,classordata-user. - A function only forwards its inputs. A wrapper, for example one that logs calls, must accept whatever the wrapped function accepts, without knowing its signature.
Python solves all three with two pieces of syntax. A star-prefixed parameter collects extra positional arguments into a tuple, and a double-star parameter collects extra keyword arguments into a dictionary. The same symbols at a call site spread a sequence or dictionary out into separate arguments. The next chapters build on the matching rules above: *args and **kwargs add two more "catch the leftovers" slots to the algorithm, and the algorithm's order of steps stays the same.
Before moving on, note one fact that you will use constantly. Python separates what the caller wrote (positional versus keyword) from what the function declared (a name in a slot). A single parameter such as species can be filled either way, and that flexibility is the reason parameter names matter.
Summary
- A parameter is a name in the
def. An argument is a value in the call. - Positional arguments match by order. Keyword arguments match by name. Positional arguments must come first in a call.
- A parameter with a default is optional, and the default is evaluated once at definition time. Use
Noneas a sentinel for mutable defaults. - Binding fills parameters from positional arguments, then keywords, then defaults. Each failure produces a specific
TypeError. inspect.signature(...).bind(...)shows how a call will be matched without running the function.
Exercise
Given def order(item, quantity=1, note=""), say what each call does: (a) order("tea", 2), (b) order("tea", note="no sugar"), (c) order(quantity=2, "tea"), (d) order("tea", item="coffee").
Show answer
(a) Binds item="tea", quantity=2, note="" and runs normally. (b) Binds item="tea", quantity=1 (the default) and note="no sugar", and runs normally. (c) Raises a SyntaxError before the program runs, because a positional argument follows a keyword argument. (d) Raises TypeError: order() got multiple values for argument 'item', because the positional "tea" already filled item.
Exercise
This function is meant to collect tags for each post, but tags leak between calls. Explain why, then rewrite it so each call starts with a fresh list. def makepost(title, tags=[]): tags.append("new") return {"title": title, "tags": tags} print(makepost("A")) print(make_post("B"))
Show answer
The default list is created once, when def runs, and every call that omits tags shares it. The second call prints tags ['new', 'new']. Fix: def make_post(title, tags=None): if tags is None: tags = [] tags.append("new") return {"title": title, "tags": tags} Now each call without tags creates its own list, so both calls print tags ['new'].
Exercise
Use inspect.signature to predict what bind() produces for def area(width, height=10) called as area(5), after apply_defaults(). Write the code and the printed result.
Show answer
import inspect def area(width, height=10): return width * height bound = inspect.signature(area).bind(5) bound.applydefaults() print(bound.arguments) It prints {'width': 5, 'height': 10}. The positional 5 fills width, and applydefaults() adds height from its default.