Lesson 8
Making Objects the Main Star!
Chapter 10: Input validation
Easier to ask for forgiveness
Python recommends a different approach.
This approach is called the Easier to Ask for Forgiveness than for Permission (EAFP).
In this approach, you do not try to police your code, but trust that most of the time they will do what they are supposed to do. On the occasion that something goes wrong, then your program can deal with it!
This is a bit like a loving parent who purposely allows their children to make mistakes, and just deal with it with love when the error happens.
Here is an example of the EAFP approach. You just let the division happen. And if a ZeroDivisionError
ever occurs, you deal with it!
1 2 3 4 5 6 |
|
The main motivation behind this style of programming is readability. The division in Line 3 is what you’re trying to do, so that should be the main star. The division by zero case is an exception, and should not be the focus of your code! They are called exceptions for a reason – because they are exceptions and not the norm! So you probably should not be too obsessed about that at the expense of the most important part of your code.
This approach might also be slightly more efficient than LBYL, since you are not actively checking the value of denominator
with an if
statement each time the function is called!