This guide explains choose good defaults without hiding errors 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
Defaults are helpful for genuinely optional behavior but harmful when they silently substitute for required information. Use explicit required parameters for decisions that should never be guessed.
When and Why to Use It
The following example focuses on a practical use of Choose Good Defaults Without Hiding Errors.
Step-by-Step Example
def calculate_shipping(weight_kg, *, express=False):
base_price = weight_kg * 2
return base_price + (10 if express else 0)
print(calculate_shipping(3))
print(calculate_shipping(3, express=True))
Understanding the Example
Weight is required because a price cannot be calculated without it. Express service is optional with a clear false default, producing 6 and 16.
Expected Output
6
16
Important Behavior and Edge Cases
Avoid a default weight or price that makes missing information look legitimate; validate required values instead.
Try It Yourself
Design a function where an email address is required but a send_copy option is optional.
Common Beginner Mistakes
- Avoid a default weight or price that makes missing information look legitimate; validate required values instead.
- 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
- Defaults are helpful for genuinely optional behavior but harmful when they silently substitute for required information.
- Weight is required because a price cannot be calculated without it.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.