Sub topic 2
Calling functions by position and by keyword
This chapter assumes you can define and call a simple function, know the basic built-in types, and can read a short traceback. It covers the two ways to pass arguments and the rules Python uses to match them to parameters.
Two ways to supply an argument
A call can identify each argument in one of two ways:
- By position. Python matches arguments to parameters in the order they were written.
- By keyword. You write
name=value, and Python matches the argument to the parameter with that name.
def area(width, height):
return width * height
print(area(3, 4)) # positional: width=3, height=4
print(area(width=3, height=4)) # keyword: same result
print(area(height=4, width=3)) # keyword order does not matterAll three calls return 12. With keywords, the order of the arguments in the call is irrelevant, because each value is matched by name.
Mixing both styles
You can use both styles in one call, but positional arguments must come first. Python fills parameters from the left with the positional values. It then matches each keyword argument by name.
def describe(name, age, city):
return f"{name}, {age}, from {city}"
print(describe("Ada", 36, city="London"))
print(describe("Ada", city="London", age=36))Putting a positional argument after a keyword argument is a SyntaxError. Python rejects it before the program runs:
describe(name="Ada", 36, "London")
# SyntaxError: positional argument follows keyword argumentHow Python binds a call
The binding happens in a fixed sequence at every call. Knowing it makes the error messages easier to predict.
The check in the last step produces most of the binding errors you will meet. A parameter can end up with no value, or with two.
def area(width, height):
return width * height
area(3) # TypeError: missing 1 required positional argument: 'height'
area(3, 4, 5) # TypeError: takes 2 positional arguments but 3 were given
area(3, width=3) # TypeError: got multiple values for argument 'width'
area(3, depth=4) # TypeError: got an unexpected keyword argument 'depth'The third case is the one that surprises people. The positional 3 already filled width, so the keyword width=3 is a second value for the same parameter.
When to use which
Positional calls are short and read well when the meaning is obvious, as in max(a, b) or area(3, 4). Keywords help when a call has several arguments of the same type, or when a bare value says nothing about its purpose.
def resize(width, height, keep_ratio):
return (width, height, keep_ratio)
resize(800, 600, True) # what does True mean?
resize(800, 600, keep_ratio=True) # clearerMany built-ins already work this way. For example, sorted(names, reverse=True) and print("a", "b", sep="-") pass their options by keyword. Passing the option by keyword makes the call self-documenting.
Summary of the rules
| Situation | Result |
|---|---|
| Positional arguments in order | Bound left to right |
| Keyword arguments in any order | Bound by name |
| Positional after keyword in a call | `SyntaxError` |
| Same parameter given twice | `TypeError: multiple values` |
| Unknown keyword name | `TypeError: unexpected keyword argument` |
| Parameter left without a value | `TypeError: missing required argument` |
Exercise
Given def box(length, width, height): ..., which of these calls is valid, and why do the others fail? (a) box(2, 3, height=4) (b) box(2, length=2, width=3) (c) box(length=2, 3, 4)
Show answer
Only (a) is valid. The positional arguments 2 and 3 fill length and width, and height is matched by name. Call (b) raises a TypeError because length receives two values, the positional 2 and the keyword length=2. It also leaves height without a value. Call (c) is a SyntaxError because the positional arguments 3 and 4 follow a keyword argument.