Sub topic 4
Passing arguments by position and by keyword
This chapter assumes you can define a function with def, you know the difference between a parameter and an argument, and you have seen return. It covers how Python matches the arguments in a call to the parameters in a definition, and which mistakes come up most often.
Two ways to match arguments to parameters
A call can give each value to a parameter in one of two ways.
- A positional argument is matched by its place in the call. The first argument goes to the first parameter, the second to the second, and so on.
- A keyword argument is matched by name. You write
name=valuein the call, and Python gives the value to the parameter with that name.
def describe_pet(name, species, age):
return f"{name} is a {age}-year-old {species}."
print(describe_pet("Rex", "dog", 4))
print(describe_pet(name="Rex", species="dog", age=4))
print(describe_pet("Rex", age=4, species="dog"))All three calls print the same sentence: Rex is a 4-year-old dog. In the second call, every argument is a keyword argument, so their order does not matter. In the third call, the first argument is positional and the other two are keyword arguments.
How Python binds a call
Before the function body runs, Python builds a mapping from parameter names to values. It follows these steps:
- It fills parameters from the positional arguments, from left to right.
- It then fills parameters from the keyword arguments, by name.
- It fills any parameter that is still empty from its default value, if it has one.
- If a parameter is still empty, or an argument has no place to go, it raises
TypeErrorbefore running any of the function's code.
This order explains most of the errors in the next sections.
The ordering rule
In a call, every positional argument must come before every keyword argument. Python reports a violation as a SyntaxError, because it is detected when the code is compiled.
def describe_pet(name, species, age):
return f"{name} is a {age}-year-old {species}."
# This line would not compile:
# describe_pet(name="Rex", "dog", 4)
# SyntaxError: positional argument follows keyword argument
print(describe_pet("Rex", species="dog", age=4))The reason is practical. Once a keyword argument has been used, Python cannot tell which parameter a later unnamed value is meant for.
Common errors
Four mistakes account for most TypeError messages about arguments. Each message names the function and the problem, so read it before changing the code.
| Mistake | Example call | Error message (shortened) |
|---|---|---|
| Too few arguments | `describe_pet("Rex", "dog")` | missing 1 required positional argument: 'age' |
| Too many arguments | `describe_pet("Rex", "dog", 4, "x")` | takes 3 positional arguments but 4 were given |
| Unknown keyword | `describe_pet("Rex", "dog", years=4)` | got an unexpected keyword argument 'years' |
| Same parameter twice | `describe_pet("Rex", "dog", 4, name="Max")` | got multiple values for argument 'name' |
The last row deserves attention. In describe_pet("Rex", "dog", 4, name="Max"), the first positional argument already fills name. The keyword argument then tries to fill it a second time. You can reproduce and catch this error:
def describe_pet(name, species, age):
return f"{name} is a {age}-year-old {species}."
try:
describe_pet("Rex", "dog", 4, name="Max")
except TypeError as error:
print(error)This prints a message ending in got multiple values for argument 'name'. The exact wording of the beginning can differ between Python versions, so do not compare error text in your own code.
Keyword arguments and default values
Keyword arguments become more useful when parameters have defaults. A caller can skip the parameters they do not care about and set only the one they need.
def connect(host, port=5432, timeout=30, use_ssl=True):
return f"{host}:{port} timeout={timeout} ssl={use_ssl}"
print(connect("db.example.com"))
print(connect("db.example.com", use_ssl=False))
print(connect("db.example.com", 5433, 10))The second call uses a keyword argument to change use_ssl without having to repeat port and timeout. With positional arguments alone, you would have to write connect("db.example.com", 5432, 30, False).
Note the order in the definition. Parameters with defaults must come after parameters without defaults. This is not allowed:
# SyntaxError: parameter without a default follows parameter with a default
# def connect(port=5432, host):
# ...The rule exists because positional matching goes from left to right. If a default parameter sat before a required one, a call with one positional argument would be ambiguous.
When to choose keywords
Python accepts either style, so the choice is about readability and safety.
- Use positional arguments when the meaning is obvious from the function name and the order is natural, as in
max(a, b)orrange(0, 10). - Use keyword arguments when the call contains several values of the same type, or booleans and numbers whose purpose is not clear.
Compare these two calls:
def resize(width, height, keep_ratio=False, smooth=True):
return (width, height, keep_ratio, smooth)
print(resize(800, 600, True, False))
print(resize(800, 600, keep_ratio=True, smooth=False))Both give the same result, but only the second can be read without looking at the definition. Keywords also protect against swapping two values of the same type, such as width and height, which Python cannot detect because both are integers.
Keyword arguments also help when the function changes. If the author adds a new parameter in the middle of a list, calls that used positions can silently shift values into the wrong parameters. Calls that used names keep working, as long as the names stay the same. This means parameter names are part of a function's public interface once other people call it with keywords.
Built-in functions use both styles
Many built-in functions accept keyword arguments, and you have probably used them already.
numbers = [3, 1, 2]
print(sorted(numbers, reverse=True)) # [3, 2, 1]
print("a", "b", "c", sep="-", end="!\n") # a-b-c!In sorted, the reverse parameter can only be passed by keyword. The chapter on / and * shows how you can write your own functions with the same restriction.
Mixing the two styles in one call
A call can combine both styles, as long as the positional arguments come first. A practical pattern is to pass the one or two essential values by position and everything optional by keyword.
def format_price(amount, currency="USD", decimals=2, symbol=True):
text = f"{amount:.{decimals}f}"
if symbol and currency == "USD":
return "$" + text
return f"{text} {currency}"
print(format_price(19.5)) # $19.50
print(format_price(19.5, "EUR")) # 19.50 EUR
print(format_price(19.5, decimals=0)) # $20
print(format_price(19.5, "EUR", symbol=False)) # 19.50 EURIn the third call, decimals=0 skips over currency and keeps its default. The value 19.5 formatted with zero decimals becomes 20 because Python rounds it. Python rounds halves to the nearest even number in some cases, so format_price(20.5, decimals=0) gives $20, not $21.
Edge cases to know
- Keyword order is free.
f(b=2, a=1)andf(a=1, b=2)are the same call. - A keyword argument cannot be given twice.
f(a=1, a=2)is aSyntaxError. - The names in a call must match the parameter names exactly, including case.
Age=4does not matchage. - Default values are not evaluated at call time. Python evaluates them once when
defruns. This matters for mutable values such as lists, and a later chapter covers it in detail. - Required parameters can still be passed by keyword. A parameter is not "keyword-only" just because you used its name.
Summary of the rules
- A positional argument is matched by place. A keyword argument is matched by name.
- Positional arguments come first in a call. Keyword arguments follow, in any order.
- No parameter may receive a value twice.
- Every parameter without a default must receive a value.
- Use keywords for clarity when a call has several similar values or flags.
Exercise
The function def make_tag(text, tag="p", css_class=None) returns an HTML string. Which of these calls raise an error, and why? (1) make_tag("hi", "h1") (2) make_tag(tag="h1", "hi") (3) make_tag("hi", text="bye") (4) make_tag("hi", css_class="big")
Show answer
Call 1 is valid: "hi" fills text and "h1" fills tag. Call 2 raises a SyntaxError because a positional argument follows a keyword argument. Call 3 raises a TypeError because "hi" already fills text, so text="bye" gives it a second value. Call 4 is valid: tag keeps its default "p" and css_class is set by keyword.
Exercise
Rewrite the call resize(1024, 768, False, True) from this chapter so that a reader can understand it without seeing the function definition. Then explain why your version is safer if the author later inserts a new parameter before keep_ratio.
Show answer
Write resize(1024, 768, keep_ratio=False, smooth=True). If a new parameter is inserted before keep_ratio, the positional version would pass False and True to the wrong parameters without any error. The keyword version still gives each value to the intended parameter, because the names have not changed.