Last modified: Oct 28, 2026

Python Keyword-Only Arguments Explained

Introduction

Python functions often require flexible parameters. Keyword-only arguments are a feature that enforces clarity in function calls. These arguments must be passed by name, not position. They improve code readability and reduce errors.

Syntax and Examples

Keyword-only arguments are defined after a * symbol in a function definition. They cannot be passed as positional arguments. Here’s a basic example:


def example(a, *, b, c=10):
    # 'a' is positional, 'b' and 'c' are keyword-only
    return a + b + c

# Valid call
result = example(1, b=2)
print(result)

13

Attempting to pass a keyword-only argument positionally raises a TypeError:


# Invalid call (raises error)
example(1, 2)

TypeError: example() takes 1 positional argument but 2 were given

Default values can be assigned to keyword-only arguments:


def greet(name, *, greeting='Hello'):
    return f"{greeting}, {name}!"

print(greet('Alice'))

Hello, Alice!

Benefits of Keyword-Only Arguments

They prevent accidental misuse of parameters. For instance, a function with many parameters becomes easier to call correctly. They also make the function’s intent explicit.

Comparison with Positional-Only Arguments

Python also supports positional-only arguments, which must be passed by position. For a contrasting approach, see Python Positional-Only Arguments Explained. While keyword-only arguments enforce clarity, positional-only arguments enforce order.

Use Cases

Keyword-only arguments are ideal for optional parameters. They are also useful when parameters have similar names. For example, in a configuration function:


def configure(host, *, port=8080, timeout=30):
    # Configuration logic here
    return {'host': host, 'port': port, 'timeout': timeout}

config = configure('localhost', port=9090)
print(config)

{'host': 'localhost', 'port': 9090, 'timeout': 30}

They also pair well with advanced features like Python Match Case: Simplified Switch Statement for structured logic.

Best Practices

Use keyword-only arguments for optional parameters. Avoid overloading functions with too many parameters. For complex logic, consider using Python Walrus Operator Explained to streamline assignments within expressions.

Conclusion

Keyword-only arguments enhance Python’s flexibility while enforcing clarity. By defining parameters after *, you ensure they’re passed by name. This practice leads to more maintainable and error-resistant code. Experiment with them in your next function design.