Sub topic 1
Quick recap: positional and keyword arguments
args and *kwargs only make sense once you are sure how Python matches the values in a call to the parameters in a definition. This chapter refreshes that matching. The rest of the tutorial builds on it.
Prerequisites
This chapter assumes you can already do the following:
- Define and call a function with
def. - Use default parameter values such as
age=1. - Read and build tuples and dictionaries.
- Loop over a dictionary with
items().
Parameters and arguments
A parameter is a name in a function definition. An argument is the value you pass for it in a call. In def area(width, height), width and height are parameters. In area(3, 4), 3 and 4 are arguments.
Python binds each argument to a parameter before the function body runs. A call can identify a parameter in two ways: by position or by name.
Positional arguments
A positional argument is matched to a parameter by its place in the call. The first value goes to the first parameter, the second value to the second, and so on.
def describe(name, species, age=1):
return f"{name} is a {species}, age {age}"
print(describe("Rex", "dog")) # Rex is a dog, age 1
print(describe("Rex", "dog", 3)) # Rex is a dog, age 3Swapping the first two values gives describe("dog", "Rex"). Python does not complain, because both are strings. You only get a wrong sentence. With positional arguments, the caller has to remember the order.
Keyword arguments
A keyword argument is written as name=value. Python matches it to the parameter with that name, so the order in the call no longer matters.
print(describe(species="cat", name="Tom")) # Tom is a cat, age 1
print(describe("Tom", age=4, species="cat")) # Tom is a cat, age 4The second call mixes both styles. "Tom" is positional and fills name. The other two values are matched by name.
Defaults make parameters optional
A parameter with a default value can be left out of the call. Here age has the default 1, so describe("Rex", "dog") works. Parameters without a default are required.
A default is evaluated once, when the function is defined, not on every call. That matters for mutable defaults such as lists.
The matching rules
Python applies these rules when it binds a call:
- Positional arguments are bound first, left to right.
- Keyword arguments are then matched by name.
- Parameters still unbound take their default values.
- A required parameter that is still unbound is an error.
In the call itself, all positional arguments must come before any keyword argument.
The errors you will meet
Each broken call below fails in a different way. Learn to recognise the messages, because the chapters ahead build on these rules.
def describe(name, species, age=1):
return f"{name} is a {species}, age {age}"
broken_calls = [
lambda: describe("Rex"), # required parameter unbound
lambda: describe("Rex", name="Rex", species="dog"), # name bound twice
lambda: describe("Rex", "dog", color="brown"), # no such parameter
lambda: describe("Rex", "dog", 3, "extra"), # too many positional values
]
for call in broken_calls:
try:
call()
except TypeError as error:
print(error)Running it prints:
describe() missing 1 required positional argument: 'species'
describe() got multiple values for argument 'name'
describe() got an unexpected keyword argument 'color'
describe() takes from 2 to 3 positional arguments but 4 were givenOne more mistake never reaches runtime. Writing describe(name="Rex", "dog") puts a positional argument after a keyword argument. Python rejects it with a SyntaxError when it compiles the file, before any code runs.
Why fixed parameters are not always enough
Every function so far has a fixed list of parameters. A call must supply at least the required ones, and it can never supply more than the list allows. That is a problem in several common cases:
- A
totalfunction should add up two numbers, or ten, or none. - A function should accept any option and pass it on to another function.
- A decorator must wrap functions whose signatures it has never seen.
The next two chapters solve these with *args and **kwargs. They are the same binding rules you just reviewed, plus two catch-all parameters that collect what the fixed ones do not take. Later chapters cover the matching * and ** syntax at call sites.
Exercise
Given def connect(host, port=8080, secure=False), which of these calls raises an error, and why? (a) connect("example.com", secure=True) (b) connect(port=9000, "example.com") (c) connect("example.com", 443, host="other.com")
Show answer
(a) works: host is bound by position, port uses its default 8080, and secure is bound by name. (b) fails with a SyntaxError, because a positional argument follows a keyword argument. (c) fails with a TypeError saying it got multiple values for argument 'host', because the first positional value already filled host and the keyword tries to fill it again.
Exercise
What does describe("Tom", age=4, species="cat") print, using the describe function from this chapter, and which parameters get their values by name?
Show answer
It prints Tom is a cat, age 4. name is bound by position, while age and species are bound by name. The order of the keyword arguments does not matter.