Positional-only
- Python course
- Beginner
- Lesson 80/116
- 4 min
Learn positional-only parameters with /.
Positional-only parameters
Parameters before a / become positional-only; they cannot be passed as keyword:
def compute(a, b, /):
return a + b
compute(1, 2) # valid
compute(a=1, b=2) # errorThis is used when parameter names are an implementation detail; so renaming them later does not break calls.
This feature was added in Python 3.8.
Why positional-only?
Positional-only parameters are ideal when the parameter name is not important for the user:
def add(x, y, /):
return x + yHere x and y can be renamed; calls still work. The call is add(3, 4).
Some functions in the standard library (len, pow) are defined this way.
Practice Write a positional-only function
Define a function called compute with a and b positional-only parameters (then /). The body does return a + b. Assign compute(3, 4) to result. Then print print(result).
Starter code
# Define the compute functionSample solution
def compute(a, b, /):
return a + b
result = compute(3, 4)
print(result)Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match positional-only features
| Term | Meaning |
|---|---|
/ |
Positional separator |
positional-only |
Cannot be keyword |
compute(1, 2) |
Valid call |
Python 3.8 |
Version |
2 Complete the positional-only call
compute(____, 2)
compute(1, 2)
Explanation: compute(1, 2) is a positional call.
3 In def f(a, /, b): ... which call is valid?
- f(a=1, 2)
- f(1, b=2) Correct answer
- f(1, 2)
- f(a=1, b=2)
Explanation: a is positional-only (passed as 1), b can be keyword.