Keyword-only
- Python course
- Beginner
- Lesson 79/116
- 4 min
Learn keyword-only parameters with *.
Keyword-only parameters
Parameters after a * become keyword-only; they cannot be passed positionally:
def create_user(name, *, role, active):
...
create_user("Ayse", role="admin", active=True) # valid
create_user("Ayse", "admin", True) # errorThis makes calls readable. role and active must be given by name.
The star separates the positional region from the keyword region.
Why keyword-only?
Keyword-only parameters make calls explicit:
send_email(to, *, subject, body, cc=None)Here subject and body cannot be passed positionally; this avoids misleading calls. send_email("a@b.com", "Merhaba", "Selam") raises an error, preventing wrong usage.
In API design this feature is common; it prevents ambiguous calls.
Practice Write a keyword-only function
Define a function called create_user with name positional, then *, then role and active keyword-only parameters. The body does print(name, role, active). Call it with create_user("Ayse", role="admin", active=True).
Starter code
# Define the create_user functionSample solution
def create_user(name, *, role, active):
print(name, role, active)
create_user("Ayse", role="admin", active=True)Expected output
Ayse admin True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In def f(a, *, b): ... which call is valid?
- f(1, b=2) Correct answer
- f(1, 2)
- f(a=1, 2)
- f(b=1, a=2)
Explanation: a positional, b after the star must be keyword.
2 Complete the keyword-only call
create_user("Ayse", ____="admin", active=True)
create_user("Ayse", role="admin", active=True)
Explanation: role="admin" is passed as keyword.
3 Match keyword-only features
| Term | Meaning |
|---|---|
* |
Region separator |
keyword-only |
Cannot be positional |
role="admin" |
Keyword call |
API design |
Use case |