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.

Easy Python 3.0+ Aug 9, 2026 Functions & basics 15 views 0 copies

Python code

17 lines
Python 3.0+
def 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

stdout
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

  1. Use `**kwargs` to collect arbitrary keyword-only arguments.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.