How to Use Keyword-Only Arguments in Python Functions
Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.
Python code
17 linesdef greet(name, *, greeting="Hello", punctuation="!"):
"""Greet someone with a customizable message using keyword-only arguments."""
message = f"{greeting}, {name}{punctuation}"
return message
if __name__ == "__main__":
# Basic call with only the positional argument
print(greet("Alice"))
# All keyword arguments specified after the *
print(greet("Bob", greeting="Hi", punctuation="?"))
# Mixing positional and keyword-only arguments
print(greet("Charlie", punctuation="..."))
# This would raise an error: greet("Dave", "Hey")
# because extra positional args are not allowed after the *
Output
Hello, Alice!
Hi, Bob?
Hello, Charlie...
How it works
The * in the function signature marks the end of positional parameters; all parameters after it are keyword-only. This enforces that you must pass them by name, preventing accidental positional errors. The default values specified in the signature apply when those arguments are omitted. The f-string formats the message cleanly, demonstrating how keyword-only args can be combined with defaults for flexible yet strict function calls.
Common mistakes
- Forgetting the `*` separator, making all params positional.
- Placing keyword-only arguments before the `*` (must be after).
- Using too many positional args in a call, causing TypeError.
Variations
- Use `**kwargs` to collect arbitrary keyword-only arguments.
- Define a function where all arguments are keyword-only by using `*` alone as the first parameter.
Real-world use cases
- APIs that require explicit parameter names to avoid breaking changes.
- Configuration functions where defaults are common but you want to force clarity.
- Database query builders that accept many optional filters safely.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.