This guide explains keyword-only parameters with * through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
A bare * in a function signature marks following parameters as keyword-only. This prevents readers from confusing unnamed positional values with sensitive options.
When and Why to Use It
The following example focuses on a practical use of Keyword-Only Parameters with *.
Step-by-Step Example
def apply_discount(price, *, percent, rounded=True):
discounted = price * (1 - percent / 100)
return round(discounted, 2) if rounded else discounted
print(apply_discount(80, percent=10))
Understanding the Example
price can be supplied positionally. percent and rounded require explicit names in the call, making the discount interpretation visible.
Expected Output
72.0
Important Behavior and Edge Cases
Calling apply_discount(80, 10) raises TypeError; the star does not mean an argument named * must be passed.
Try It Yourself
Make a send_notification function where urgent is keyword-only.
Common Beginner Mistakes
- Calling apply_discount(80, 10) raises TypeError; the star does not mean an argument named * must be passed.
- Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- A bare * in a function signature marks following parameters as keyword-only.
- price can be supplied positionally.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.