Sub topic 2
Calling Functions by Position and by Keyword
This chapter assumes you can define and call a simple Python function, know the built-in types (numbers, strings, lists, dicts, None), and can read a short traceback. It covers how Python matches the arguments in a call to the parameters in a definition. Later chapters build on this matching with default values, *, /, *args and **kwargs.
Two ways to supply an argument
An argument can be passed in two ways:
- By position. Python matches it to a parameter by where it appears in the call.
- By keyword. You write
name=value, and Python matches it to the parameter with that name.
Here is a function with three parameters:
def describe_user(name, age, city):
return f"{name} ({age}) from {city}"
print(describe_user("Ada", 36, "London"))
print(describe_user(city="London", name="Ada", age=36))
print(describe_user("Ada", city="London", age=36))All three calls return Ada (36) from London. The first uses only positional arguments. The second uses only keyword arguments, so their order doesn't matter. The third mixes the two: "Ada" is positional and fills name, and the other two are matched by name.
The binding procedure
When you call a function, Python builds a mapping from parameter names to values. This is called binding. For ordinary parameters the procedure is:
- Each positional argument fills a parameter, left to right, starting with the first parameter.
- Each keyword argument fills the parameter with that name. It is an error if the name doesn't exist, or if that parameter is already filled.
- Any parameter still empty gets its default value. If it has no default, the call fails.
Steps 1 and 2 explain why positional arguments must come first in a call. Positions are counted from the start of the argument list, so a positional argument after a keyword argument is ambiguous. Python rejects this when it compiles your code:
describe_user(name="Ada", 36, "London")
# SyntaxError: positional argument follows keyword argumentA SyntaxError appears before any code in the file runs, so you can't catch it at runtime.
Order of evaluation
Python evaluates the argument expressions in the order you write them, not in the order of the parameters. The difference shows up when the expressions have side effects:
def describe_user(name, age, city):
return f"{name} ({age}) from {city}"
def show(label, value):
print("evaluating", label)
return value
result = describe_user(
age=show("age", 36),
name=show("name", "Ada"),
city=show("city", "London"),
)
print(result)This prints evaluating age, evaluating name, evaluating city, then Ada (36) from London. The function body doesn't run until all the arguments exist.
Why keywords help
Keyword arguments make a call readable without opening the definition. Compare:
def send(message, urgent, retry, log):
return (message, urgent, retry, log)
send("deploy done", True, False, True)
send("deploy done", urgent=True, retry=False, log=True)The second call says what each True and False means. Standard library code does this constantly:
print("a", "b", sep="-") # a-b
print(sorted(["bb", "a", "ccc"], key=len, reverse=True)) # ['ccc', 'bb', 'a']Keywords also let you skip parameters. If a function has several defaults, a caller can set only the one they care about. That is the main reason keyword arguments and defaults are usually taught together.
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
print(greet("Ada", punctuation="?")) # Hello, Ada?Without keywords, you would have to pass "Hello" again just to reach punctuation. Defaults get their own chapter, so here the point is only that omitted parameters get filled in step 3 of the procedure.
Mixing the two styles
The usual convention is to pass the first one or two obvious arguments by position and everything else by keyword. For example, open("data.txt", encoding="utf-8") reads clearly because the file name is obvious and the encoding would be a mystery if passed by position.
Mixing has one rule, which follows from the binding procedure: a parameter can be filled only once. If a positional argument has already filled a parameter, you can't also give it by keyword.
def describe_user(name, age, city):
return f"{name} ({age}) from {city}"
describe_user("Ada", 36, name="Ada")
# TypeError: describe_user() got multiple values for argument 'name'Here "Ada" fills name (position 1), 36 fills age, and then name="Ada" tries to fill name a second time. The error message says "multiple values", which is accurate, even though both values happen to be equal.
The four common failures
Each way a call can fail in the binding procedure produces its own TypeError. Knowing the four patterns lets you diagnose most call errors from the message alone. A later chapter looks at these in more detail.
def describe_user(name, age, city):
return f"{name} ({age}) from {city}"
describe_user("Ada", 36)
# TypeError: describe_user() missing 1 required positional argument: 'city'
describe_user("Ada", 36, "London", "UK")
# TypeError: describe_user() takes 3 positional arguments but 4 were given
describe_user("Ada", 36, town="London")
# TypeError: describe_user() got an unexpected keyword argument 'town'
describe_user("Ada", 36, "London", age=37)
# TypeError: describe_user() got multiple values for argument 'age'| Message contains | Binding step that failed | Typical cause |
|---|---|---|
| `missing ... required` | Step 3 | You forgot an argument, or misspelled a keyword so it didn't fill its parameter |
| `takes N positional arguments but M were given` | Step 1 | Too many positional arguments |
| `unexpected keyword argument` | Step 2 | The name doesn't match any parameter |
| `multiple values for argument` | Step 2 | A parameter was filled by position and again by keyword |
A misspelled keyword is worth a note. A call like describe_user("Ada", 36, citty="London") raises unexpected keyword argument 'citty'. A call that omits the parameter instead raises missing ... 'city'. Both point at the same line, but the first message names the exact wrong word.
Keyword names are part of the interface
When you pass an argument by keyword, you make the parameter's name part of the contract between caller and function. If the function's author later renames city to town, every caller using city=... breaks, while positional callers keep working. The reverse risk exists too: if someone inserts a new parameter in the middle of the list, positional callers silently pass values to the wrong parameters, and keyword callers are unaffected.
# Version 1
def area(width, height):
return width * height
# Version 2: someone adds a parameter in the middle
def area(width, depth, height):
return width * depth * height
area(3, 4) # TypeError: missing 'height' (loud, good)
area(3, height=4) # TypeError: missing 'depth' (loud, good)These two failures are loud, which is the better outcome. The silent case happens when the new parameter has a default, or when two adjacent parameters have the same type and swapped order still produces a plausible number.
Later chapters show how to make this choice part of the function definition, by forcing callers to use keywords (*) or forbidding them (/). For now, remember the rule that applies to any function you didn't write: if the call isn't self-explanatory, use keywords.
Quick reference
- A parameter is a name in the
defline. An argument is a value in the call. - Positional arguments are matched left to right. Keyword arguments are matched by name.
- In a call, all positional arguments come before all keyword arguments.
- Each parameter can be filled exactly once.
- Argument expressions are evaluated in written order.
- Four messages cover most binding failures:
missing,takes N positional arguments,unexpected keyword, andmultiple values.
Exercise
Given def box(width, height, depth): return width * height * depth, which of these calls raise an error, and what kind? (a) box(2, 3, depth=4) (b) box(2, width=3, depth=4) (c) box(depth=4, 2, 3) (d) box(2, 3)
Show answer
(a) works and returns 24. (b) raises TypeError ("got multiple values for argument 'width'"), because 2 fills width by position and width=3 fills it again. (c) raises SyntaxError ("positional argument follows keyword argument") before the program runs. (d) raises TypeError ("missing 1 required positional argument: 'depth'").
Exercise
A function is defined as def move(x, y, speed). A teammate changes it to def move(x, y, z, speed). Explain what happens to the calls move(1, 2, 5) and move(1, 2, speed=5).
Show answer
Both calls now raise TypeError for a missing required argument. move(1, 2, 5) fills x, y and z, so speed is missing. move(1, 2, speed=5) fills x, y and speed, so z is missing. Both fail loudly. If z had a default value, the first call would instead silently pass 5 as z and leave speed unset, which is the dangerous case.