Course contentsShow
← Python
Lesson 147 of 1,0603. Functions and ModularizationFree lesson

Enforcing Keyword-Only Arguments

You will learn to use the asterisk separator to force callers to provide specific arguments by name, preventing ambiguity in function usage.

In this lesson, you will learn how to use the asterisk (*) symbol to force callers to provide specific arguments by name, ensuring your code remains clear and unambiguous.

Why Force Keyword Arguments?

Up until now, you’ve learned that Python is very flexible: you can pass arguments by their position or by their name. However, as functions grow in complexity, relying on position can lead to bugs. If you have a function that accepts several similar pieces of data (like calculate_shipping(weight, price, tax)), a caller might accidentally swap the weight and price, which could cause your program to behave incorrectly.

By enforcing keyword-only arguments, you require the person calling your function to explicitly type the name of the argument, making the intent obvious.

The Asterisk Separator

You can force this behavior by placing a single * in your function’s parameter list. Any parameters listed after the * must be passed as keyword arguments.

Look at this example:

def create_user(username, *, email, is_admin):
    print(f"User: {username}, Email: {email}, Admin: {is_admin}")

# This works perfectly:
create_user("jdoe", email="jdoe@example.com", is_admin=True)

# This will raise a TypeError:
# create_user("jdoe", "jdoe@example.com", True)

In the example above, username is a positional argument, so it can be passed normally. However, because of the *, both email and is_admin must be provided using their names (e.g., email="..."). If you try to pass them simply as values in order, Python will stop the program and throw an error.

Why This Matters

Using this technique acts as a guardrail for your code. It prevents "mystery arguments" where it’s unclear what a value represents. When you enforce keyword-only arguments, you are documenting the purpose of each input directly in the function call, making your code much easier for others (or your future self) to read and maintain.

Key Takeaway: By placing a * in your parameter list, you force all subsequent arguments to be passed by keyword, removing ambiguity and making your function calls self-documenting.