Lesson 8
Making Objects the Main Star!
Chapter 10: Input validation
LBYL vs. EAFP
Here is another example.
In LBYL, you check whether an item is a key in my_dict before you append the value of my_dict[item] to value.
1 2 3 | |
In EAFP, you just go ahead and append my_dict[item] to value. If a KeyError is raised, then you skip this case.
1 2 3 4 5 | |
In the first version with LBYL, you are trying hard to make sure that a KeyError does not occur in the first place! Thus, the if statement somehow ends up becoming part of your algorithm.
Compare that to the second version with EAFP which just lets KeyError happen (occasionally), so there is no unnecessary if checks to confuse the reader about the main intention of the code (Line 3)